Class: Cloudflare::D1Database
- Inherits:
-
Object
- Object
- Cloudflare::D1Database
- Defined in:
- lib/cloudflare_workers.rb
Overview
D1Database wraps a Cloudflare D1 JS binding. The public API is modelled on CRuby’s ‘sqlite3-ruby` gem (`SQLite3::Database`) so that the calling code reads identically:
# sqlite3-ruby on CRuby:
rows = db.execute("SELECT * FROM users WHERE id = ?", [1])
# homura on Opal (+ async):
rows = db.execute("SELECT * FROM users WHERE id = ?", [1]).__await__
Every query method returns a JS Promise. Use ‘.__await__` inside a `# await: true` route block to unwrap it synchronously (Opal compiles `.__await__` to a native JS `await`).
Results are always Hashes — ‘results_as_hash` is effectively hardcoded to `true`. This matches the common `db.results_as_hash = true` convention in the sqlite3-ruby world and gives downstream ORM code a ready-made Hash-per-row interface to build on.
Class Method Summary collapse
Instance Method Summary collapse
- #exec(sql) ⇒ Object
-
#execute(sql, bind_params = []) ⇒ Object
Execute a SQL statement with optional bind parameters.
-
#execute_batch(sql) ⇒ Object
Execute one or more raw SQL statements separated by semicolons.
-
#execute_insert(sql, bind_params = []) ⇒ Object
Execute a write statement (INSERT / UPDATE / DELETE) and return a metadata Hash with ‘changes`, `last_row_id`, `duration`, etc.
-
#get_first_row(sql, bind_params = []) ⇒ Object
Execute and return only the first row (or nil).
-
#initialize(js) ⇒ D1Database
constructor
A new instance of D1Database.
-
#prepare(sql) ⇒ Object
—- low-level D1 API (prepare/bind/all/first/run) —————.
Constructor Details
#initialize(js) ⇒ D1Database
Returns a new instance of D1Database.
635 636 637 |
# File 'lib/cloudflare_workers.rb', line 635 def initialize(js) @js = js end |
Class Method Details
.flatten_meta(result) ⇒ Object
688 689 690 691 692 693 694 695 696 697 |
# File 'lib/cloudflare_workers.rb', line 688 def self.(result) return result unless result.is_a?(Hash) nested = result['meta'] return result unless nested.is_a?(Hash) %w[last_row_id changes duration size_after rows_read rows_written].each do |k| result[k] = nested[k] unless result.key?(k) end result end |
Instance Method Details
#exec(sql) ⇒ Object
712 713 714 715 |
# File 'lib/cloudflare_workers.rb', line 712 def exec(sql) js = @js `(#{js}.exec ? #{js}.exec(#{sql}) : #{js}.prepare(#{sql}).run())` end |
#execute(sql, bind_params = []) ⇒ Object
Execute a SQL statement with optional bind parameters. Returns a JS Promise resolving to an Array of Hashes; the build-time auto-await pass rewrites the usual Sinatra call sites so app code can stay ‘db.execute(…)` instead of spelling `.__await__`.
db.execute("SELECT * FROM users") → Array<Hash>
db.execute("SELECT * FROM users WHERE id = ?", [1]) → Array<Hash>
db.execute("INSERT INTO users (name) VALUES (?)", ["alice"]) → Array<Hash> (empty for writes)
649 650 651 652 653 |
# File 'lib/cloudflare_workers.rb', line 649 def execute(sql, bind_params = []) stmt = prepare(sql) stmt = stmt.bind(*bind_params) unless bind_params.empty? stmt.all end |
#execute_batch(sql) ⇒ Object
Execute one or more raw SQL statements separated by semicolons. Useful for schema migrations. Returns the raw async D1 exec result.
701 702 703 |
# File 'lib/cloudflare_workers.rb', line 701 def execute_batch(sql) exec(sql) end |
#execute_insert(sql, bind_params = []) ⇒ Object
Execute a write statement (INSERT / UPDATE / DELETE) and return a metadata Hash with ‘changes`, `last_row_id`, `duration`, etc. Returns a JS Promise resolving to that metadata Hash.
The raw D1 ‘run()` payload nests these fields under `meta`:
{ 'success' => true, 'meta' => { 'last_row_id' => 7, ... }, 'results' => [...] }
sqlite3-ruby exposes them at the top level. To keep the documented “sqlite3-ruby compatible” surface and still leave the raw shape available, flatten the common keys to the top level.
= db.execute_insert("INSERT INTO users (name) VALUES (?)", ["alice"])
['last_row_id'] # → 7 (flattened convenience)
['meta']['last_row_id'] # → 7 (raw D1 shape)
678 679 680 681 682 683 |
# File 'lib/cloudflare_workers.rb', line 678 def execute_insert(sql, bind_params = []) stmt = prepare(sql) stmt = stmt.bind(*bind_params) unless bind_params.empty? raw = stmt.run D1Database.(raw) end |
#get_first_row(sql, bind_params = []) ⇒ Object
Execute and return only the first row (or nil). Returns a JS Promise resolving to a Hash or nil.
db.get_first_row("SELECT * FROM users WHERE id = ?", [1]) → Hash or nil
659 660 661 662 663 |
# File 'lib/cloudflare_workers.rb', line 659 def get_first_row(sql, bind_params = []) stmt = prepare(sql) stmt = stmt.bind(*bind_params) unless bind_params.empty? stmt.first end |
#prepare(sql) ⇒ Object
—- low-level D1 API (prepare/bind/all/first/run) —————
707 708 709 710 |
# File 'lib/cloudflare_workers.rb', line 707 def prepare(sql) js = @js D1Statement.new(`#{js}.prepare(#{sql})`) end |