Class: Cybertrain::DB::Connection

Inherits:
Object
  • Object
show all
Defined in:
cybertrain/db/connection.rb

Overview

One SQLite database handle. Not thread-safe on its own: threads share connections through Cybertrain::DB::Pool, which hands each one to a single thread at a time.

Instance Method Summary collapse

Instance Method Details

#begin!(immediate: false) ⇒ nil

Opens a transaction, or one more nesting level of the open one, for code that keeps its rescue in a plain method (Spinel cannot compile a yielding method with a rescue everywhere: NOTES rules 32/45). immediate: true issues BEGIN IMMEDIATE, which takes SQLite’s write lock now instead of at the first write: a read-then-write transaction then waits for other writers at its start, where a deferred one would fail with SQLITE_BUSY at its first write once another connection has written in between. Only the outermost level opens anything, so immediate: on a nested call changes nothing (SQLite cannot upgrade an open transaction). Pair every begin! with exactly one commit! or rollback!:

c.begin!(immediate: true) begin c.execute(“UPDATE accounts SET balance = balance - ? WHERE id = ?”, [n, from]) c.execute(“UPDATE accounts SET balance = balance + ? WHERE id = ?”, [n, to]) rescue JSON::NestingError, JSON::ParserError, StandardError => e c.rollback! raise e end c.commit!

Parameters:

  • immediate (Boolean) (defaults to: false) —

    BEGIN IMMEDIATE instead of BEGIN (outermost level only)

Returns:

  • (nil)

Raises:

  • (Cybertrain::DB::Error) —

    when the connection is closed, when the enclosing transaction is gone (SQLite rolled it back on its own after an error the application rescued), or when SQLite refuses the BEGIN (SQLITE_BUSY once the busy handler gives up, for BEGIN IMMEDIATE)



358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'cybertrain/db/connection.rb', line 358

def begin!(immediate: false)
  raise Error, "connection closed (transaction)" if @closed

  # A depth above 0 while SQLite is in autocommit means the enclosing
  # transaction is gone: SQLite rolled it back on its own after
  # SQLITE_FULL / IOERR / BUSY and the app's block rescued that and went
  # on. Nesting into it would run this block without a transaction
  # and never COMMIT; starting a fresh one here would commit this part
  # while the outer COMMIT then fails as if everything rolled back.
  # Raising is the only honest answer; Pool#check_in resets the depth
  # when the connection comes back.
  if @transaction_depth > 0 && SQLite3.sqlite3_get_autocommit(@db) != 0
    raise Error, "transaction: the enclosing transaction is no longer open (SQLite rolled it back " \
                 "after an error); nothing nested in it can be committed"
  end
  if @transaction_depth > 0
    @transaction_depth += 1
    return nil
  end
  refuse_if_transaction_gone(immediate ? "BEGIN IMMEDIATE" : "BEGIN")

  exec_waiting(immediate ? "BEGIN IMMEDIATE" : "BEGIN")
  @transaction_depth = 1
  nil
end

#commit! ⇒ nil

Ends one level opened by #begin!. A nested level only counts down; the outermost one COMMITs. A failed COMMIT (deferred foreign key, SQLITE_BUSY) leaves SQLite inside the transaction, so it is rolled back before the COMMIT error is re-raised.

Returns:

  • (nil)

Raises:

  • (Cybertrain::DB::Error) —

    when the connection is closed, when no transaction is open, or when the COMMIT fails (everything is rolled back then)



393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'cybertrain/db/connection.rb', line 393

def commit!
  raise Error, "connection closed (commit!)" if @closed
  raise Error, "commit!: no transaction is open on this connection" if @transaction_depth == 0
  if @transaction_depth > 1
    @transaction_depth -= 1
    return nil
  end

  @transaction_depth = 0
  begin
    exec_waiting("COMMIT")
  rescue Error => e
    abandon_transaction!
    raise e
  end
  nil
end

#in_transaction? ⇒ Boolean

Whether a transaction is open on this connection, however it was opened (#begin!, a transaction block or a BEGIN run as SQL): SQLite is out of autocommit mode.

Returns:

  • (Boolean)

Raises:

  • (Cybertrain::DB::Error) —

    when the connection is closed



287
288
289
290
# File 'cybertrain/db/connection.rb', line 287

def in_transaction?
  raise Error, "connection closed (in_transaction?)" if @closed
  SQLite3.sqlite3_get_autocommit(@db) == 0
end

#rollback! ⇒ nil

Ends one level opened by #begin! after an error. The outermost level ROLLBACKs; a nested level only counts down and leaves the decision to the outermost one, exactly as a raise out of a nested transaction block does: re-raise after it, so the outer level rolls back too (a nested rollback! followed by a normal end commits the nested writes along with the outer ones: there are no savepoints). Never raises, so a rescue clause can call it without masking the exception it is about to re-raise; on a connection with nothing open it does nothing.

Returns:

  • (nil)


422
423
424
425
426
427
428
429
# File 'cybertrain/db/connection.rb', line 422

def rollback!
  if @transaction_depth > 1
    @transaction_depth -= 1
    return nil
  end
  abandon_transaction!
  nil
end

#statements_run ⇒ Integer

How many statements #execute and #execute_models have run on this connection (exec_script’s are not counted), for a test that asserts how many queries something costs:

before = Cybertrain::DB.with { |c| c.statements_run }
Article.includes(:comments).to_a.each { |a| a.comments.size }
Cybertrain::DB.with { |c| c.statements_run } - before  # => 2

Returns:



277
278
279
# File 'cybertrain/db/connection.rb', line 277

def statements_run
  @statements_run
end

#variable_limit ⇒ Integer

The most ? binds one statement may carry (SQLITE_LIMIT_VARIABLE_NUMBER: 32766 by default since SQLite 3.32, 999 before, 250000 in the bundled build), asked of the library once and then cached. Model.insert_all_into sizes its chunks by it.

Returns:

Raises:

  • (Cybertrain::DB::Error) —

    when the connection is closed



262
263
264
265
266
# File 'cybertrain/db/connection.rb', line 262

def variable_limit
  raise Error, "connection closed (variable_limit)" if @closed
  @variable_limit = SQLite3.sqlite3_limit(@db, SQLite3::LIMIT_VARIABLE_NUMBER, -1) if @variable_limit < 0
  @variable_limit
end