skaidb 1.4.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0514ffe373981266d475977fd65030cbf7bdc8a2ba568c77b80afe963904e242
4
- data.tar.gz: a7a1ce25bf193955ae0f765df14245ab0cf1a4d6ff6902f712291666646b0061
3
+ metadata.gz: c1684623cac79f6c62a066686a0a6f6af3af9141a7434eb4b3a297a7c0d4d9f1
4
+ data.tar.gz: 62a78c8e58e4ce110e2ae3ce52ccc2dd246bb9481aeee68d80292b46e17c2d2f
5
5
  SHA512:
6
- metadata.gz: e60490e9a1e5ef0381199c96981bf18a19cfd915da2926ce6ac3395bb31cdb20be2d3c5135a1cc7b6172ab48dae15877d0479ea6aa86b1aa0da0219e062f70e9
7
- data.tar.gz: 9a8a3422a05a1eb3294bd67425a6d59291924254d6b9acac4002923d14867b3f30205a21446b254c2957a51090a76508deb69df6abd1058b5bdef96383402d95
6
+ metadata.gz: c85ce23da9ad6e8fb7a372190ace6ef40226319fa601ecbbc2477d891a272a1303b919494d2b10f98aae441c0583802b2ce729c381b000da021bbdef12933f5d
7
+ data.tar.gz: 82d387c4e1ce106331ac57dc8cf20225018f8fa491fc73ab8954062eb3624d3b191882b32ca801cdc7edbffd2922990bebbd83050e2ee8cceef24a6712491046
data/CHANGELOG.md CHANGED
@@ -4,6 +4,62 @@ All notable changes to the skaidb Ruby driver. The format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow
5
5
  [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [1.5.0] - 2026-11-15
8
+
9
+ ### Added
10
+ - **`Skaidb::TransactionConflict`**, a `QueryError` raised for a server
11
+ error whose message starts with `transaction conflict:` — what a
12
+ standalone server (≥ 0.346) answers a `COMMIT` with when another writer
13
+ changed a row the transaction writes after its `BEGIN`. Nothing was
14
+ applied, the transaction is over and the connection stays usable; the
15
+ message is the server's, unchanged. Every call that runs a statement
16
+ raises it (`exec`, `exec_params`, `exec_prepared`, `exec_batch`,
17
+ `stream`), and `rescue Skaidb::QueryError` catches it as before. It is a
18
+ statement error: it does not count against a pool member's health, close
19
+ the connection or cause a re-dial.
20
+ - **`conn.transaction(attempts: 3, begin: "BEGIN") { |conn| … }`** sends
21
+ `begin`, runs the block, sends `COMMIT` and returns the block's value. A
22
+ `COMMIT` refused with `TransactionConflict` runs the whole transaction
23
+ again from `begin` — up to `attempts` runs in all, with no pause between
24
+ them — so the block must be safe to run more than once; the conflict of
25
+ the last attempt is raised. A refused `begin` is raised without running
26
+ the block or sending anything else. A block that does not run to its end
27
+ (an exception, `break`, `throw`) is rolled back and never retried, and
28
+ what the `ROLLBACK` answers never replaces the block's exception. Any
29
+ other `COMMIT` error is raised with no retry and no `ROLLBACK`. `begin:`
30
+ is the opening statement, sent as given (`BEGIN ATOMIC` or
31
+ `BEGIN ATOMIC PARTITION (col = lit)` on a cluster). `attempts` below 1,
32
+ or no block, raises `ArgumentError` before anything is sent.
33
+ - Inside `transaction` a connection that loses its transport does not
34
+ re-dial: the `ConnectionError` is not retried, no `ROLLBACK` is sent to a
35
+ new session, and a statement the block still runs after rescuing the
36
+ failure raises `ConnectionError` instead of being committed on its own
37
+ there. The first statement after `transaction` returns re-dials as always.
38
+ - **`pool.transaction(attempts: 3, begin: "BEGIN", affinity: nil) { |conn| … }`**:
39
+ the same helper on one checked-out connection, held for every attempt and
40
+ returned afterwards.
41
+
42
+ ### Fixed
43
+ - A statement cut short between its request and its reply by something
44
+ other than a transport error — `Timeout.timeout`, an `Interrupt`,
45
+ `Thread#kill` — left the reply on the socket with `usable?` still `true`,
46
+ and the next statement on that connection read it as its own: a
47
+ `SELECT 1` returned the rows of the statement that had timed out. The
48
+ connection is now marked broken at that point, so `usable?` is `false`, a
49
+ pool closes it on check-in and the next statement re-dials. `exec`,
50
+ `exec_params`, `exec_batch` and the first frame of a `stream` are covered.
51
+ `transaction` relies on it: a block cut short that way is not followed by
52
+ a `ROLLBACK` that would wait for the outstanding reply.
53
+ - A broken connection is re-dialled by whichever statement comes next. A
54
+ parameterised statement the connection had already prepared
55
+ (`exec_params`, `exec_batch`) took its id from the cache before that
56
+ check and sent it down the old socket, so a connection that ran only
57
+ such statements raised `ConnectionError` on every call after a transport
58
+ failure and never recovered. The cache is now read after the re-dial,
59
+ which empties it. `exec_prepared` with an id from before the failure
60
+ raises `ConnectionError` (`connection is broken; prepare the statement
61
+ again`).
62
+
7
63
  ## [1.4.1] - 2026-10-31
8
64
 
9
65
  ### Fixed
@@ -224,6 +280,7 @@ batches, a 2 500-row stream, error handling, and the `drivers` table showing
224
280
  because it is a bundled gem since Ruby 3.4.
225
281
  - The example moved to `examples/basic.rb`.
226
282
 
283
+ [1.5.0]: https://github.com/porcupin26/skaidb-ruby/compare/v1.4.1...v1.5.0
227
284
  [1.4.1]: https://github.com/porcupin26/skaidb-ruby/compare/v1.4.0...v1.4.1
228
285
  [1.4.0]: https://github.com/porcupin26/skaidb-ruby/compare/v1.3.0...v1.4.0
229
286
  [1.3.0]: https://github.com/porcupin26/skaidb-ruby/compare/v1.2.0...v1.3.0
data/README.md CHANGED
@@ -12,9 +12,9 @@ and the result behaves like `PG::Result`. **Pure standard library** (`socket`,
12
12
  `openssl`, `securerandom`, `bigdecimal`) — no third-party code, one file,
13
13
  Ruby 2.7 through 3.4. It speaks skaidb's binary protocol directly:
14
14
  SCRAM-SHA-256 authentication, server-side prepared statements with typed
15
- parameters, one-round-trip batches, streamed result sets, multi-seed failover,
16
- transparent reconnect, TLS and a connection pool that balances across the
17
- cluster's members.
15
+ parameters, one-round-trip batches, streamed result sets, a retrying
16
+ transaction helper, multi-seed failover, transparent reconnect, TLS and a
17
+ connection pool that balances across the cluster's members.
18
18
 
19
19
  - Repository: <https://github.com/porcupin26/skaidb-ruby>
20
20
  - RubyGems: <https://rubygems.org/gems/skaidb>
@@ -55,13 +55,13 @@ Xcode command-line tools on macOS). `gem install skaidb` and vendoring reuse
55
55
  the `bigdecimal` already installed.
56
56
 
57
57
  Or vendor the single file: copy
58
- [`lib/skaidb.rb`](https://github.com/porcupin26/skaidb-ruby/blob/v1.4.1/lib/skaidb.rb)
58
+ [`lib/skaidb.rb`](https://github.com/porcupin26/skaidb-ruby/blob/v1.5.0/lib/skaidb.rb)
59
59
  into your project and `require_relative` it. It has no dependencies beyond
60
60
  Ruby's standard library.
61
61
 
62
62
  Every release is also attached as a `.gem` to its
63
63
  [GitHub release](https://github.com/porcupin26/skaidb-ruby/releases) for
64
- installs without registry access: `gem install ./skaidb-1.4.1.gem`.
64
+ installs without registry access: `gem install ./skaidb-1.5.0.gem`.
65
65
 
66
66
  ## Quick start
67
67
 
@@ -104,7 +104,8 @@ end
104
104
  - [Streams (`CREATE STREAM`)](#streams-create-stream) — `subscribe`
105
105
  - [Type mapping](#type-mapping)
106
106
  - [Errors](#errors)
107
- - [Transactions](#transactions)
107
+ - [Transactions](#transactions) — `transaction`, `TransactionConflict`,
108
+ hand-written `BEGIN`/`COMMIT`
108
109
  - [Thread safety](#thread-safety)
109
110
  - [Client identification and version](#client-identification-and-version)
110
111
  - [Compatibility](#compatibility)
@@ -155,7 +156,9 @@ through.
155
156
  `timeout` bounds the TCP dial only. Reads have no deadline: a peer that is
156
157
  alive but silent blocks the caller, as in ruby-pg. `close` deliberately does
157
158
  not take the connection's lock, so another thread can break a stuck read by
158
- closing the connection.
159
+ closing the connection. A statement cut short while its reply is outstanding
160
+ — by `Timeout.timeout`, an `Interrupt`, `Thread#kill` — leaves the connection
161
+ marked broken, so the next statement re-dials instead of reading that reply.
159
162
 
160
163
  ### TLS
161
164
 
@@ -202,8 +205,8 @@ the server regardless of this setting.
202
205
  ### Health
203
206
 
204
207
  - `conn.usable?` — no round-trip. `true` unless the connection is closed, was
205
- left out of sync by a transport error or an undrainable abandoned stream, or
206
- is currently mid-stream.
208
+ left out of sync by a transport error, a round trip cut short or an
209
+ undrainable abandoned stream, or is currently mid-stream.
207
210
  - `conn.closed` / `conn.finished?` — `true` after `close`.
208
211
 
209
212
  ## Statements and parameters
@@ -429,24 +432,113 @@ StandardError
429
432
  └── Skaidb::Error # also: invalid consistency, pool closed
430
433
  ├── Skaidb::ConnectionError # dial/auth/transport failures, framing, closed connection
431
434
  └── Skaidb::QueryError # the server rejected the statement; bad parameters
435
+ └── Skaidb::TransactionConflict # a COMMIT refused: another writer changed a row it writes
432
436
  ```
433
437
 
434
438
  - A server `Error` frame is a **statement** error (`QueryError`); the
435
439
  connection stays usable.
440
+ - A server error whose message starts with `transaction conflict:` is a
441
+ `TransactionConflict`, from every call that runs a statement. It is a
442
+ `QueryError`, so `rescue Skaidb::QueryError` catches it too; see
443
+ [Transactions](#transactions).
436
444
  - A transport failure (`ConnectionError`) marks the connection broken; the
437
- next statement re-dials, or a pool replaces it.
445
+ next statement re-dials, or a pool replaces it. So does anything else that
446
+ cuts a statement short between its request and its reply (an `Interrupt`,
447
+ a `Timeout`); that exception propagates as it is.
438
448
  - `ArgumentError` for `Pool.new(maxsize: 0)` or an unknown
439
449
  `load_balancing`/`idle_order`, for `Skaidb::Uuid.new` of a string that
440
- is not a UUID, and for `stream` parameters that are not an Array.
450
+ is not a UUID, for `stream` parameters that are not an Array, and for
451
+ `transaction` with `attempts` below 1 or without a block.
441
452
 
442
453
  ## Transactions
443
454
 
444
- skaidb autocommits every statement. There is no `BEGIN` on this driver's API;
445
- where your server supports statement-level transaction control, issue
446
- `BEGIN`/`COMMIT`/`ROLLBACK` as ordinary statements. **On a cluster,
447
- transaction control is not available** — a `BEGIN` there is refused by the
448
- server as a statement error. See the server documentation for what your
449
- deployment supports.
455
+ skaidb autocommits every statement outside a transaction. A transaction is
456
+ ordinary statements on **one connection**: an opening statement, the
457
+ statements, then `COMMIT` or `ROLLBACK`. `conn.transaction` does that around
458
+ a block and returns the block's value:
459
+
460
+ ```ruby
461
+ conn.transaction do |c|
462
+ c.exec_params("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [10, 1])
463
+ c.exec_params("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [10, 2])
464
+ end
465
+
466
+ conn.transaction(attempts: 5, begin: "BEGIN ATOMIC") { |c| … }
467
+ pool.transaction { |c| … } # one checked-out connection for all of it
468
+ ```
469
+
470
+ `begin:` is the opening statement, sent as given: `"BEGIN"` (the default) on
471
+ a standalone server; a cluster takes `BEGIN ATOMIC` or
472
+ `BEGIN ATOMIC PARTITION (col = lit)`. The rest is the same on both.
473
+
474
+ **Conflicts.** A standalone server (≥ 0.346) refuses a `COMMIT` when another
475
+ writer changed a row the transaction writes after its `BEGIN`. Nothing was
476
+ applied, the transaction is over, and the connection is back in autocommit
477
+ and stays usable. The driver raises `Skaidb::TransactionConflict` for it — a
478
+ `QueryError` carrying the server's message, recognised by its
479
+ `transaction conflict:` prefix, from `exec` and every other call as well as
480
+ from the helper. Running the whole transaction again from its opening
481
+ statement is safe, and that is what `transaction` does: up to `attempts` runs
482
+ in all (default 3), with no pause between them — the other writer has
483
+ already finished, and the next run reads the rows as they are now. So **the
484
+ block must be safe to run more than once**, and should do nothing outside the
485
+ database that a repeat would do twice. The conflict of the last attempt is
486
+ raised.
487
+
488
+ What else `transaction` does:
489
+
490
+ - The opening statement is refused: its error is raised, the block never
491
+ runs and nothing else is sent.
492
+ - The block does not run to its end (an exception, `break`, `throw`):
493
+ `ROLLBACK` is sent, and the block's exception propagates unchanged
494
+ whatever the `ROLLBACK` itself answers. Nothing is retried, a
495
+ `TransactionConflict` raised inside the block included.
496
+ - Any other `COMMIT` error is raised as it is, with no retry and no
497
+ `ROLLBACK`: a `COMMIT` that fails has ended the transaction.
498
+ - A transport failure is the usual `ConnectionError` and is not retried. The
499
+ transaction lived on the socket that died, so until `transaction` returns
500
+ the connection does not re-dial: no `ROLLBACK` is sent, and a statement the
501
+ block still runs after rescuing the failure raises `ConnectionError`
502
+ instead of running on a new session. The same goes for a block cut short
503
+ in the middle of a round trip (an `Interrupt`, a `Timeout`): the reply is
504
+ still on its way, so nothing more is written to that socket.
505
+ - `pool.transaction(attempts: 3, begin: "BEGIN", affinity: nil)` checks one
506
+ connection out, runs every attempt on it, and returns it afterwards.
507
+
508
+ Written by hand, the same transaction is:
509
+
510
+ ```ruby
511
+ conn.exec("BEGIN") # if this raises, stop here
512
+ begin
513
+ conn.exec_params("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [10, 1])
514
+ conn.exec_params("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [10, 2])
515
+ rescue StandardError
516
+ begin
517
+ conn.exec("ROLLBACK") if conn.usable?
518
+ rescue Skaidb::Error
519
+ nil # the clean-up never replaces the error it follows
520
+ end
521
+ raise
522
+ end
523
+ conn.exec("COMMIT") # Skaidb::TransactionConflict: nothing was applied; run it again from BEGIN
524
+ ```
525
+
526
+ Two rules hold however the statements are sent:
527
+
528
+ - **One connection for the whole transaction.** Statements sent on another
529
+ connection are not part of it, so with a pool check one connection out
530
+ (`pool.with`) and keep it until the `COMMIT`; a statement another thread
531
+ sends on that connection meanwhile is part of it. A `ConnectionError` ends
532
+ the transaction with its socket; the connection's next statement re-dials
533
+ and runs on a new session, in autocommit. That is why the example sends
534
+ `ROLLBACK` only while the connection is `usable?`.
535
+ - **Stop if `BEGIN` fails.** No transaction is open, so every statement sent
536
+ after it would be committed on its own.
537
+
538
+ A statement that fails inside a transaction leaves it open: decide between
539
+ `ROLLBACK` and carrying on. A `ROLLBACK` with no transaction open succeeds on
540
+ a server ≥ 0.347 and is a statement error (`no transaction in progress`) on
541
+ an older one.
450
542
 
451
543
  ## Thread safety
452
544
 
@@ -464,7 +556,7 @@ frame after every handshake. It shows up as `client_name = 'ruby'` /
464
556
 
465
557
  ```sql
466
558
  SELECT client_name, client_version FROM drivers;
467
- -- ruby | 1.4.1
559
+ -- ruby | 1.5.0
468
560
  ```
469
561
 
470
562
  The server records the row asynchronously, so a `SELECT` immediately after
data/docs/api.md CHANGED
@@ -52,6 +52,9 @@ Raises `Skaidb::Error` before dialing for an unknown `auth_mechanism`, a
52
52
  (which names the failing row index; earlier rows stay applied).
53
53
  - `exec_prepared(id, params, consistency) → Result` — run a statement by the
54
54
  id `prepare_server` returned, with an Array of typed values in `?` order.
55
+ The id is valid on the socket that prepared it: on a broken connection
56
+ this raises `ConnectionError` instead of re-dialing, and `prepare_server`
57
+ hands out a new id.
55
58
  - `prepare_server(sql) → [id, nparams] | nil` — prepare a statement with `?`
56
59
  placeholders on the server; `nil` when the server refuses. Cached per
57
60
  connection (240 entries); the cache is cleared on re-dial.
@@ -77,13 +80,55 @@ Raises `Skaidb::Error` before dialing for an unknown `auth_mechanism`, a
77
80
  keyset cursor, sleeping `poll` seconds when caught up. `after:` is the last
78
81
  `"id"` (an opaque String) already handled.
79
82
 
83
+ ### Transactions
84
+
85
+ `transaction(attempts: 3, begin: "BEGIN") { |conn| … } → the block's value`
86
+ runs the block inside a transaction on this connection: it sends `begin`,
87
+ yields the connection, then sends `COMMIT`.
88
+
89
+ - `begin:` is the opening statement, sent as given: `"BEGIN"` on a standalone
90
+ server, `"BEGIN ATOMIC"` or `"BEGIN ATOMIC PARTITION (col = lit)"` on a
91
+ cluster.
92
+ - A `COMMIT` refused with `TransactionConflict` (a standalone server ≥ 0.346:
93
+ another writer changed a row the transaction writes after its `BEGIN`;
94
+ nothing was applied) runs the whole transaction again from `begin`, up to
95
+ `attempts` runs in all with no pause between them. The block may therefore
96
+ run more than once: it must be safe to repeat and should do nothing outside
97
+ the database that a repeat would do twice. The conflict of the last
98
+ attempt is raised.
99
+ - `begin` refused: its error is raised, the block never runs and nothing
100
+ else is sent.
101
+ - The block does not run to its end (an exception of any class, `break`,
102
+ `throw`, a `return` out of it): `ROLLBACK` is sent and the exception
103
+ propagates unchanged, whatever the `ROLLBACK` itself answers — an error
104
+ from it is ignored. Nothing is retried, a `TransactionConflict` raised
105
+ inside the block included.
106
+ - Any other `COMMIT` error is raised as it is, with no retry and no
107
+ `ROLLBACK` (a `COMMIT` that fails has ended the transaction).
108
+ - A transport failure is the usual `ConnectionError` and is not retried.
109
+ Until `transaction` returns the connection does not re-dial: no `ROLLBACK`
110
+ is sent, and a statement the block runs after rescuing the failure raises
111
+ `ConnectionError` (`connection lost inside a transaction; …`). A
112
+ `ConnectionError` from the `COMMIT` leaves its outcome unknown.
113
+ - A block cut short in the middle of a round trip (an `Interrupt`, a
114
+ `Timeout`, `Thread#kill`) leaves a reply on its way, so the connection is
115
+ not `usable?` and nothing more is written to it: no `ROLLBACK`. The
116
+ transaction ends with that socket, which the next statement after
117
+ `transaction` replaces.
118
+ - Raises `ArgumentError`, before anything is sent, when `attempts` is not an
119
+ Integer ≥ 1 or no block is given.
120
+
121
+ The whole transaction runs on this one connection, so no other thread may
122
+ use it meanwhile.
123
+
80
124
  ### State
81
125
 
82
126
  - `consistency` / `consistency=` — the default level (`0`/`1`/`2`; the setter
83
127
  accepts anything `Consistency.resolve` does).
84
- - `usable?` — `false` once closed, once a transport error broke the socket,
85
- or while a stream is in flight (including one abandoned through external
86
- iteration). No round-trip.
128
+ - `usable?` — `false` once closed, once a transport error broke the socket
129
+ or a round trip was cut short with its reply outstanding, or while a
130
+ stream is in flight (including one abandoned through external iteration).
131
+ No round-trip.
87
132
  - `endpoint` — the member the connection reached, as the `"host:port"` it
88
133
  dialed (it changes when a re-dial lands on another member).
89
134
  - `closed`, `finished?` — `true` after `close`.
@@ -93,12 +138,17 @@ Raises `Skaidb::Error` before dialing for an unknown `auth_mechanism`, a
93
138
  ### Reconnect
94
139
 
95
140
  A transport failure raises `Skaidb::ConnectionError` and marks the
96
- connection broken. The next `exec`/`exec_params`/`exec_batch`/`stream`
141
+ connection broken. A statement cut short between its request and its reply
142
+ by anything else (an `Interrupt`, `Timeout.timeout`, `Thread#kill`) marks it
143
+ broken too, since that reply is still on its way; the exception propagates
144
+ as it is. The next `exec`/`exec_params`/`exec_batch`/`stream`
97
145
  re-dials across the original seeds (a pooled connection: in the pool's
98
146
  order, usable members first and the one it lost last), re-authenticates,
99
147
  re-sends `Hello`, re-runs `USE`, and starts with an empty prepared-statement
100
148
  cache. If the re-dial fails, that statement raises `ConnectionError` and the
101
- one after it tries again.
149
+ one after it tries again. Inside `transaction` there is no re-dial: the
150
+ transaction ended with its socket, so every further statement raises
151
+ `ConnectionError` until the helper returns.
102
152
 
103
153
  ## `Skaidb::Result`
104
154
 
@@ -131,6 +181,10 @@ A thread-safe pool balanced across the cluster's members — see
131
181
 
132
182
  - `with(affinity: nil) { |conn| … }` — check out, yield, check in; returns
133
183
  the block's value.
184
+ - `transaction(attempts: 3, begin: "BEGIN", affinity: nil) { |conn| … }` —
185
+ `Connection#transaction` on one checked-out connection, held for every
186
+ attempt and checked in afterwards; returns the block's value. The
187
+ arguments are checked before a connection is checked out.
134
188
  - `checkout(affinity: nil) → Connection` — an idle connection to the member
135
189
  the policy picks, or a new one. Never blocks. `affinity` (any Hash key;
136
190
  `nil` = pool-wide) scopes `read_your_writes`.
@@ -143,9 +197,9 @@ A thread-safe pool balanced across the cluster's members — see
143
197
 
144
198
  `load_balancing` (`:random`, `:round_robin`, `:least_latency`) and
145
199
  `idle_order` (`:lifo`, `:fifo`) take a Symbol or a String. Raises
146
- `ArgumentError` for `maxsize < 1`, `eject_errors < 1` or an unknown
147
- `load_balancing`/`idle_order`, and `Skaidb::Error` on checkout from a closed
148
- pool.
200
+ `ArgumentError` for `maxsize < 1`, `eject_errors < 1`, an unknown
201
+ `load_balancing`/`idle_order` or a `transaction` with `attempts` below 1 or
202
+ no block, and `Skaidb::Error` on checkout from a closed pool.
149
203
 
150
204
  ## `Skaidb::Uuid`
151
205
 
@@ -173,6 +227,14 @@ otherwise.
173
227
  message is the server's), or a parameter could not be bound
174
228
  (placeholder/parameter mismatch, out-of-range Integer, non-finite Float or
175
229
  BigDecimal, unsupported type). The connection stays usable.
230
+ - `Skaidb::TransactionConflict < QueryError` — the server refused a `COMMIT`
231
+ because another writer changed a row the transaction writes after its
232
+ `BEGIN` (a standalone server ≥ 0.346). Raised by every call that runs a
233
+ statement, for a server error whose message starts with
234
+ `Skaidb::TransactionConflict::PREFIX` (`"transaction conflict:"`); the
235
+ message is the server's. Nothing was applied, the transaction is over and
236
+ the connection stays usable, in autocommit; running the whole transaction
237
+ again from `BEGIN` is safe, which is what `transaction` does.
176
238
 
177
239
  ## Codec helpers
178
240
 
@@ -93,6 +93,23 @@ Rows arrive chunk by chunk; the driver holds one chunk at a time. See
93
93
  [streaming.md](streaming.md), in particular what happens when you leave the
94
94
  block early.
95
95
 
96
+ ## Transactions
97
+
98
+ ```ruby
99
+ conn.transaction do |c| # BEGIN, the block, COMMIT; returns the block's value
100
+ c.exec_params("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [10, 1])
101
+ c.exec_params("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [10, 2])
102
+ end
103
+ ```
104
+
105
+ A block that raises is rolled back. A `COMMIT` the server refuses because
106
+ another writer changed a row the transaction writes raises
107
+ `Skaidb::TransactionConflict` with nothing applied, and `transaction` then
108
+ runs the block again (three runs in all by default), so the block must be
109
+ safe to run more than once. On a cluster pass the opening statement:
110
+ `conn.transaction(begin: "BEGIN ATOMIC") { |c| … }`. Details:
111
+ [api.md](api.md#transactions).
112
+
96
113
  ## Errors
97
114
 
98
115
  ```ruby
@@ -105,7 +122,8 @@ rescue Skaidb::ConnectionError => e # transport/handshake trouble; next stateme
105
122
  end
106
123
  ```
107
124
 
108
- Both inherit from `Skaidb::Error`.
125
+ Both inherit from `Skaidb::Error`. `Skaidb::TransactionConflict` is a
126
+ `QueryError`.
109
127
 
110
128
  ## Close
111
129
 
data/docs/pooling.md CHANGED
@@ -44,6 +44,7 @@ Skaidb::Pool.new(
44
44
  )
45
45
 
46
46
  pool.with(affinity: nil) { |conn| … } # the block's value
47
+ pool.transaction(attempts: 3, begin: "BEGIN", affinity: nil) { |conn| … } # the block's value
47
48
  pool.checkout(affinity: nil) -> Skaidb::Connection
48
49
  pool.checkin(conn)
49
50
  pool.members -> Array of Hashes (see "Watching it")
@@ -161,6 +162,14 @@ the same in every skaidb driver
161
162
  and will fail its first statement with `Skaidb::ConnectionError`; that
162
163
  failure marks it broken, so `checkin` discards it and the next checkout
163
164
  gets a fresh one. Retry the statement in that case if it is safe to.
165
+ - A transaction belongs to one connection. `pool.transaction { |conn| … }`
166
+ checks one out, runs `Connection#transaction` on it (`begin`, the block,
167
+ `COMMIT`, the whole of it again when the `COMMIT` is refused with
168
+ `Skaidb::TransactionConflict`) and checks it in afterwards; separate
169
+ `pool.with` calls may each get a different connection, and statements
170
+ sent that way are not one transaction. A `TransactionConflict` is a
171
+ statement error: it does not count against the member and the connection
172
+ goes back to the idle set.
164
173
  - `close` marks the pool closed, closes the idle connections and stops the
165
174
  background thread; connections checked out at the time are closed when
166
175
  they are returned. `checkout` on a closed pool raises `Skaidb::Error`.
data/lib/skaidb.rb CHANGED
@@ -35,7 +35,7 @@ require "bigdecimal"
35
35
  module Skaidb
36
36
  # The package version — the single source of truth. The gemspec reads it,
37
37
  # and it is what the driver reports to the server in the Hello frame.
38
- VERSION = "1.4.1"
38
+ VERSION = "1.5.0"
39
39
 
40
40
  # Base class for every error raised by this driver.
41
41
  class Error < StandardError; end
@@ -48,6 +48,35 @@ module Skaidb
48
48
  # stays usable for the next query.
49
49
  class QueryError < Error; end
50
50
 
51
+ # The server refused a COMMIT because another writer changed a row the
52
+ # transaction writes after its BEGIN. Nothing was applied and the
53
+ # transaction is over: the connection is back in autocommit and stays
54
+ # usable, and running the whole transaction again from BEGIN is safe —
55
+ # which is what Connection#transaction does. A QueryError like any other
56
+ # statement error, so +rescue Skaidb::QueryError+ catches it too; the
57
+ # message is the server's.
58
+ class TransactionConflict < QueryError
59
+ # What the server's message starts with (PROTOCOL.md §6 rule 6). Only the
60
+ # prefix is matched: the rest of the text may change.
61
+ PREFIX = "transaction conflict:"
62
+ end
63
+
64
+ # Internal: the error for a server Error frame's message — a
65
+ # TransactionConflict when it starts with the conflict prefix, a QueryError
66
+ # otherwise, the message unchanged either way.
67
+ def self.statement_error(message)
68
+ (message.start_with?(TransactionConflict::PREFIX) ? TransactionConflict : QueryError).new(message)
69
+ end
70
+
71
+ # Internal: the argument checks of Connection#transaction and
72
+ # Pool#transaction, made before anything is sent.
73
+ def self.check_transaction_arguments(attempts, has_block)
74
+ raise ArgumentError, "transaction needs a block" unless has_block
75
+ return if attempts.is_a?(Integer) && attempts >= 1
76
+
77
+ raise ArgumentError, "attempts must be an Integer >= 1, got #{attempts.inspect}"
78
+ end
79
+
51
80
  # Consistency levels — how many replicas must acknowledge/answer.
52
81
  module Consistency
53
82
  ONE = 0
@@ -715,6 +744,9 @@ module Skaidb
715
744
  @broken = false
716
745
  # A stream is in flight, so the socket sits mid-reply (see stream).
717
746
  @streaming = false
747
+ # The transaction helper is between its BEGIN and its COMMIT/ROLLBACK,
748
+ # so a lost socket must not be re-dialled (see ensure_live!).
749
+ @in_transaction = false
718
750
  @prepared = {}
719
751
  @last_prepare_error = nil
720
752
  # Retained so a reconnect repeats the original connect exactly.
@@ -926,6 +958,82 @@ module Skaidb
926
958
  n
927
959
  end
928
960
 
961
+ # Run the block inside a transaction on this connection and return the
962
+ # block's value: +begin+, the block (handed the connection), COMMIT.
963
+ #
964
+ # conn.transaction do |c|
965
+ # c.exec_params("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [10, 1])
966
+ # c.exec_params("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [10, 2])
967
+ # end
968
+ #
969
+ # A COMMIT the server refuses with TransactionConflict (another writer
970
+ # changed a row the transaction writes; nothing was applied) starts the
971
+ # whole thing again from +begin+ — up to +attempts+ runs in all, with no
972
+ # pause between them: the other writer has already finished, and the next
973
+ # run reads the rows as they are now. So the block may run MORE THAN
974
+ # ONCE: it must be safe to repeat, and should do nothing outside the
975
+ # database that a repeat would do twice. The conflict of the last attempt
976
+ # is raised.
977
+ #
978
+ # +begin+ is the opening statement, sent as given: "BEGIN" on a
979
+ # standalone server, "BEGIN ATOMIC" or "BEGIN ATOMIC PARTITION (col =
980
+ # lit)" on a cluster.
981
+ #
982
+ # - +begin+ refused: its error is raised, the block never runs and
983
+ # nothing else is sent (the block's statements would autocommit one by
984
+ # one).
985
+ # - The block does not run to its end — an exception of any class,
986
+ # +break+, +throw+ or a +return+ out of it: ROLLBACK is sent, and what
987
+ # the block was leaving with carries on unchanged whatever the ROLLBACK
988
+ # itself answers. Nothing is retried, a TransactionConflict raised in
989
+ # the block included.
990
+ # - Any other COMMIT error is raised as it is. A failed COMMIT has ended
991
+ # the transaction, so no ROLLBACK follows and nothing is retried.
992
+ # - A transport failure is the usual ConnectionError and is not retried.
993
+ # The transaction lived on the socket that died, so until the helper
994
+ # returns the connection does not re-dial: no ROLLBACK is sent, and a
995
+ # statement the block still runs after rescuing the failure raises
996
+ # ConnectionError instead of autocommitting on a new session. The same
997
+ # goes for a block cut short in the middle of a round trip (an
998
+ # Interrupt, a Timeout): the reply is still on its way, so nothing more
999
+ # is written to that socket.
1000
+ #
1001
+ # The whole transaction runs on this one connection, so no other thread
1002
+ # may use it meanwhile. +attempts+ below 1, or no block, is an
1003
+ # ArgumentError raised before anything is sent.
1004
+ def transaction(attempts: 3, begin: "BEGIN")
1005
+ opening = binding.local_variable_get(:begin) # +begin+ is a keyword, so the local has no other name
1006
+ Skaidb.check_transaction_arguments(attempts, block_given?)
1007
+
1008
+ enclosing = @in_transaction
1009
+ attempt = 0
1010
+ begin
1011
+ attempt += 1
1012
+ committing = false
1013
+ exec(opening)
1014
+ @in_transaction = true
1015
+ finished = false
1016
+ begin
1017
+ value = yield self
1018
+ finished = true
1019
+ ensure
1020
+ rollback_quietly unless finished
1021
+ end
1022
+ committing = true
1023
+ exec("COMMIT")
1024
+ value
1025
+ rescue TransactionConflict
1026
+ # Only a refused COMMIT is run again; a conflict the block raised
1027
+ # was rolled back above, and one from +begin+ opened nothing.
1028
+ raise unless committing && attempt < attempts
1029
+
1030
+ @in_transaction = enclosing
1031
+ retry
1032
+ ensure
1033
+ @in_transaction = enclosing
1034
+ end
1035
+ end
1036
+
929
1037
  # Stream a result set: yields one row Hash at a time while holding a
930
1038
  # single chunk, instead of buffering the whole result. For exports and
931
1039
  # large scans.
@@ -1000,8 +1108,7 @@ module Skaidb
1000
1108
  @mutex.synchronize do
1001
1109
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1002
1110
  begin
1003
- write_frame(req)
1004
- r = Reader.new(read_frame)
1111
+ r = Reader.new(round_trip(req))
1005
1112
  rescue ConnectionError
1006
1113
  observe_failure
1007
1114
  raise
@@ -1016,7 +1123,7 @@ module Skaidb
1016
1123
  what = params.empty? ? "streaming" : "parameterised streaming (skaidb >= 0.330)"
1017
1124
  raise QueryError, "server does not support #{what}: #{msg}"
1018
1125
  end
1019
- raise QueryError, msg
1126
+ raise Skaidb.statement_error(msg)
1020
1127
  when 1
1021
1128
  return Result.new(fields: [], rows: [], cmd_tuples: r.u64, kind: :mutation) # not row-producing
1022
1129
  when 2
@@ -1056,7 +1163,7 @@ module Skaidb
1056
1163
  live = false
1057
1164
  when 3
1058
1165
  live = false
1059
- raise QueryError, fr.text
1166
+ raise Skaidb.statement_error(fr.text)
1060
1167
  else
1061
1168
  # Mid-stream the server sends only RowsChunk, RowsEnd or Error.
1062
1169
  # Anything else means we no longer know where the reply ends, so
@@ -1090,10 +1197,12 @@ module Skaidb
1090
1197
  # server declines the statement kind (DDL, session statements) so the
1091
1198
  # caller falls back to text binding. Cached per connection.
1092
1199
  def prepare_server(sql)
1093
- hit = @prepared[sql]
1094
- return hit if hit
1095
1200
  raise ConnectionError, "connection is closed" if @closed
1201
+ # Before the cache is read: a re-dial empties it, and a cached id must
1202
+ # not send a statement down a socket that is broken.
1096
1203
  ensure_live!
1204
+ hit = @prepared[sql]
1205
+ return hit if hit
1097
1206
 
1098
1207
  sql_bytes = sql.dup.force_encoding("UTF-8").b
1099
1208
  req = [2].pack("C") + [sql_bytes.bytesize].pack("V") + sql_bytes
@@ -1116,9 +1225,12 @@ module Skaidb
1116
1225
  end
1117
1226
  end
1118
1227
 
1119
- # Execute a prepared statement with TYPED parameters.
1228
+ # Execute a prepared statement with TYPED parameters. The id belongs to
1229
+ # the socket that prepared it, so a broken connection is not re-dialled
1230
+ # here: prepare_server does that, and hands out a new id.
1120
1231
  def exec_prepared(id, params, consistency)
1121
1232
  raise ConnectionError, "connection is closed" if @closed
1233
+ raise ConnectionError, "connection is broken; prepare the statement again" if @broken
1122
1234
 
1123
1235
  req = +([3, consistency].pack("CC") + [id].pack("V") + [params.length].pack("v"))
1124
1236
  params.each do |p|
@@ -1210,6 +1322,10 @@ module Skaidb
1210
1322
  def ensure_live!
1211
1323
  raise ConnectionError, "connection is closed" if @closed
1212
1324
  return unless @broken
1325
+ # A transaction lives on the socket that carried its BEGIN. Re-dialling
1326
+ # inside the helper would run the rest of the block, and the COMMIT, on
1327
+ # a new session with no transaction open: each statement autocommitted.
1328
+ raise ConnectionError, "connection lost inside a transaction; not re-dialling until it ends" if @in_transaction
1213
1329
 
1214
1330
  @prepared.clear
1215
1331
  begin
@@ -1338,6 +1454,19 @@ module Skaidb
1338
1454
 
1339
1455
  # -- query --
1340
1456
 
1457
+ # The transaction helper's clean-up after a block that did not run to its
1458
+ # end. It runs while something else is unwinding, so it never raises: a
1459
+ # ROLLBACK the server refuses (one before 0.347 answers "no transaction in
1460
+ # progress" when nothing is open) or that dies in transport must not
1461
+ # replace what the block left with. Not sent on a connection that is not
1462
+ # usable — its socket died, or was left in the middle of a reply: the
1463
+ # transaction goes with the socket.
1464
+ def rollback_quietly
1465
+ exec("ROLLBACK") if usable?
1466
+ rescue StandardError
1467
+ nil
1468
+ end
1469
+
1341
1470
  def run(sql, consistency)
1342
1471
  raise ConnectionError, "connection is closed" if @closed
1343
1472
  ensure_live!
@@ -1380,10 +1509,7 @@ module Skaidb
1380
1509
  def request(req)
1381
1510
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1382
1511
  frame = begin
1383
- @mutex.synchronize do
1384
- write_frame(req)
1385
- read_frame
1386
- end
1512
+ @mutex.synchronize { round_trip(req) }
1387
1513
  rescue ConnectionError
1388
1514
  observe_failure
1389
1515
  raise
@@ -1392,6 +1518,23 @@ module Skaidb
1392
1518
  Reader.new(frame)
1393
1519
  end
1394
1520
 
1521
+ # Write a request and read the first frame of its reply (the caller holds
1522
+ # @mutex). Leaving in between — on a transport error, but also on an
1523
+ # Interrupt, a Timeout or Thread#kill, which no rescue here sees — means
1524
+ # the reply is still on its way: the socket no longer sits at a request
1525
+ # boundary, and the next statement would read this one's reply as its
1526
+ # own. So the connection is marked broken: usable? turns false, a pool
1527
+ # drops it, and the next statement re-dials.
1528
+ def round_trip(req)
1529
+ answered = false
1530
+ write_frame(req)
1531
+ frame = read_frame
1532
+ answered = true
1533
+ frame
1534
+ ensure
1535
+ @broken = true unless answered
1536
+ end
1537
+
1395
1538
  def observe_failure
1396
1539
  @observer.note_failure(@endpoint) if @observer && @endpoint
1397
1540
  end
@@ -1414,7 +1557,7 @@ module Skaidb
1414
1557
  when 2 # Ddl
1415
1558
  Result.new(fields: [], rows: [], cmd_tuples: 0, kind: :ddl)
1416
1559
  when 3 # Error — a statement error, connection stays usable
1417
- raise QueryError, r.text
1560
+ raise Skaidb.statement_error(r.text)
1418
1561
  else
1419
1562
  raise ConnectionError, "unknown response tag #{tag}"
1420
1563
  end
@@ -1746,6 +1889,20 @@ module Skaidb
1746
1889
  end
1747
1890
  end
1748
1891
 
1892
+ # Run the block inside a transaction on ONE checked-out connection and
1893
+ # return the block's value: Connection#transaction, with the same
1894
+ # +attempts+ and +begin+, on a connection held for the whole transaction
1895
+ # — every attempt included — and returned afterwards. +affinity+ scopes
1896
+ # read-your-writes, as in +with+.
1897
+ #
1898
+ # pool.transaction { |conn| conn.exec_params("UPDATE … WHERE id = $1", [id]) }
1899
+ def transaction(attempts: 3, begin: "BEGIN", affinity: nil, &block)
1900
+ opening = binding.local_variable_get(:begin) # +begin+ is a keyword, so the local has no other name
1901
+ Skaidb.check_transaction_arguments(attempts, block_given?)
1902
+
1903
+ with(affinity: affinity) { |conn| conn.transaction(attempts: attempts, begin: opening, &block) }
1904
+ end
1905
+
1749
1906
  # The members as the pool sees them, for monitoring: one Hash each with
1750
1907
  # +:endpoint+ (what the pool dials), +:canonical+ (the member's own name,
1751
1908
  # once discovered), +:state+ (+:ready+, +:ejected+, +:resyncing+,
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: skaidb
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.4.1
4
+ version: 1.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - skaidb contributors
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-10-31 00:00:00.000000000 Z
11
+ date: 2026-11-15 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: bigdecimal