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.



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/hecks/adapters/driven/d1.rb', line 112

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

    = settings[:account_id]  || settings["account_id"]
  database_id = settings[:database_id] || settings["database_id"]
  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 = (settings[:domain] || settings["domain"] || aggregate.name).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.



108
109
110
# File 'lib/hecks/adapters/driven/d1.rb', line 108

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).



154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/hecks/adapters/driven/d1.rb', line 154

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



171
172
173
174
175
176
177
# File 'lib/hecks/adapters/driven/d1.rb', line 171

def append(entry)
  @db.execute(
    "INSERT INTO #{quoted_entry_table} (aggregate_id, operation, state, mirrors) VALUES (?, ?, ?, ?)",
    [entry.id, entry.operation, JSON.generate(entry.state), 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.



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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/hecks/adapters/driven/d1.rb', line 239

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

  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), JSON.generate(entry.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), JSON.generate(entry.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



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

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

#delete(id) ⇒ Object



291
292
293
294
295
296
# File 'lib/hecks/adapters/driven/d1.rb', line 291

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



329
330
331
332
333
334
# File 'lib/hecks/adapters/driven/d1.rb', line 329

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



336
337
338
339
340
341
342
343
344
345
346
# File 'lib/hecks/adapters/driven/d1.rb', line 336

def each_saga
  return enum_for(:each_saga) unless block_given?

  @db.execute(
    "SELECT process_manager, correlation, state, memory 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)
  end
end

#entriesObject



194
195
196
197
198
199
200
201
202
203
204
# File 'lib/hecks/adapters/driven/d1.rb', line 194

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



305
306
307
308
309
310
311
312
313
314
315
# File 'lib/hecks/adapters/driven/d1.rb', line 305

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



144
145
146
147
148
149
# File 'lib/hecks/adapters/driven/d1.rb', line 144

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



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

def persistence_capabilities = [:atomic_put]

#project(entry) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/hecks/adapters/driven/d1.rb', line 179

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



298
299
300
301
302
303
# File 'lib/hecks/adapters/driven/d1.rb', line 298

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



206
207
208
209
210
# File 'lib/hecks/adapters/driven/d1.rb', line 206

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

#save(instance) ⇒ Object



212
213
214
215
216
# File 'lib/hecks/adapters/driven/d1.rb', line 212

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:) ⇒ 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.



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

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

#tableObject



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

def table = @aggregate.storage_name