Skip to content

Commit b66aab5

Browse files
Fix bugs found by the independent pre-release check; E2E on every supported Ruby (#49)
## Summary Fixes for the issues found by an independent pre-release check of `main` (7194e3b) against real PostgreSQL 16, MySQL 8.4 and SQLite on Ruby 3.1–4.0. Each fix comes with E2E coverage that fails on `main`. **Fixes** - **`Timeout` inside `transaction` committed the partial work on Ruby 3.1/3.2 (all drivers).** timeout < 0.4 exits the block with `throw`, which `transaction` treated as success. - For `rubyVersion` < 3.3, the generated `transaction` now records normal completion. If the block exits without completing or raising while the loaded timeout is < 0.4 (`timeout_exits_with_throw?`), it rolls back. - The generated Gemfile adds `gem 'timeout', '>= 0.4'`. - Output for `rubyVersion` >= 3.3 is unchanged. - **SQLite numbered parameters were bound in the wrong order.** sqlc writes `sqlc.arg` as `?N` on SQLite, but the generated code bound params positionally. - `sqlc.slice` followed by a named arg raised `RangeException`. - Mixing repeated `sqlc.arg` with `?` silently returned wrong rows. This also affected `:batch*`. - The sqlite3 driver now scans the SQL, skipping literals and comments, and rewrites `?N` to `?`. It binds params in occurrence order, repeating values when a param appears more than once. - **pg: json/jsonb parameters `true`/`false` failed.** `encode_json` now JSON-encodes booleans as well as Arrays. - **Query names `Raise`/`Rand`/`Format` shadowed Kernel methods** the generated class calls. They are now generation errors (`Code::KERNEL_METHODS`). A unit test scans the generated examples and golden files for unreserved bare Kernel calls. - **Keyword order.** Required keywords now come before optional ones (`def m(lim:, name_filter: nil)`), so generated code stays RuboCop-clean (`Style/KeywordParametersOrder`). Binding order is unchanged. - **README.** - The fiber-scheduler claim now says mysql2 prepared statements block the scheduler; use threads. - The Transactions section documents the timeout behaviour and when parent-object calls reuse the transaction's connection. **Test coverage** - E2E now runs on Ruby 3.1, 3.2, 3.3, 3.4 and 4.0 for all three engines. - On 3.1/3.2, `scripts/tests/generate_examples.rb` regenerates the examples for that `rubyVersion` (Struct rows) into a scratch dir (`EXAMPLES_DIR`), and the jobs install from `Gemfile.e2e`. - The tests build rows with keywords, so they work for both `Data` and `Struct`. - New E2E cases: - transactions: Timeout during a DB call and during Ruby code; `break`/`return`/`throw` semantics; `Thread#kill`; nested savepoint rollback; parent-object calls inside a transaction - pg: deferred FK failing at COMMIT, terminated backend - mysql2: KILLed connection - JSON value types - SQLite mixed placeholders (direct and `:batchone`) - named `:copyfrom` - generated-method concurrency (pg under `Sync`, mysql2 across threads) - seeded randomized `:copyfrom`, batch and concurrent-transaction plans - New examples queries cover the cases above. Fixtures were recaptured (`scripts/tests/capture_fixtures.rb`) and goldens updated. **Follow-up in this PR: mysql2 Fiber concurrency and full E2E coverage** - **mysql2 queries now run concurrently under `Sync`.** - The mysql2 driver now quotes parameters client-side (`quote`, using `Mysql2::Client#escape`; hex literals for binary strings; unsupported types raise `TypeError`). This is the same approach as ActiveRecord's mysql2 adapter. - It binds them with a literal- and comment-aware `bind_params` and sends one `Client#query`. There are no server-side prepared statements anymore. - E2E tests cover the concurrency (generated methods under `Sync`), quoting and injection, and the absence of prepared statements. - **E2E coverage of every documented feature.** `docs/Coverage.md` maps each README claim to the E2E test(s) per engine. A unit test fails if a referenced test does not exist. - **New CI jobs.** - Option-variant E2E jobs: `moduleName: MyApp::Db` for all engines, plus pg `preparedStatements: false` running the whole pg suite. - `tests/end2end_options.rb` (rename, exactTableNames, overrides, global options, several query files, `generateTypes: false`, generated-Gemfile-only load). - The 3.1/3.2 jobs install from the generated Gemfiles. - **New checks inside the suites.** - Automatic runtime RBS checks of every value returned by generated methods. - Row frozen / pattern-matching assertions. - More types and engine-specific gaps: isolation actually applied, SQLite lock modes, logger, enums, names, outer-join embeds, batch non-atomicity. - **Testing policy** in CLAUDE.md and docs/Testing.md: every supported feature needs an E2E test per engine (listed in docs/Coverage.md); bug fixes start with a failing E2E test; unit tests only where E2E cannot reach. ## Checklist - [x] `examples/` is regenerated (`rake sqlc_generate_process`) and committed - [x] Tests added or updated (`rake test`, and `rake end2end_*` when the generated code changes) - [x] The generated code stays RuboCop-clean (`rake rubocop`) and Steep-clean (`rake steep`) - [x] Labelled (`bug`, `enhancement`, `documentation`, or `breaking`) so the release notes are grouped correctly --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Doron Eli Rachman <doron050@gmail.com>
1 parent 7194e3b commit b66aab5

111 files changed

Lines changed: 11948 additions & 1646 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/tests.yml‎

Lines changed: 157 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -63,13 +63,17 @@ jobs:
6363
run: ruby -Ilib -Itest -e 'Dir["test/*_test.rb"].sort.each { |file| require File.expand_path(file) }'
6464

6565
end2end-pg:
66-
name: End-to-End (PostgreSQL, Ruby ${{ matrix.ruby-version }})
66+
name: End-to-End (PostgreSQL, Ruby ${{ matrix.ruby-version }}, ${{ matrix.variant }})
6767
runs-on: ubuntu-latest
6868

6969
strategy:
7070
fail-fast: false
7171
matrix:
72-
ruby-version: ['3.3', '4.0']
72+
ruby-version: ['3.1', '3.2', '3.3', '3.4', '4.0']
73+
variant: ['default']
74+
include:
75+
- ruby-version: '4.0'
76+
variant: 'module-no-prepared'
7377

7478
services:
7579
postgres:
@@ -88,14 +92,43 @@ jobs:
8892
8993
env:
9094
POSTGRES_HOST: 127.0.0.1
95+
EXAMPLES_DRIVER: pg
96+
EXAMPLES_MODULE: ${{ matrix.variant == 'module-no-prepared' && 'MyApp::Db' || 'PgCodegen' }}
97+
PREPARED_STATEMENTS: ${{ matrix.variant == 'module-no-prepared' && 'false' || 'true' }}
98+
BUNDLE_GEMFILE: ${{ (matrix.ruby-version == '3.1' || matrix.ruby-version == '3.2') && 'Gemfile.e2e' || 'Gemfile' }}
9199

92100
steps:
93101
- uses: actions/checkout@v7
94102

95103
- uses: ruby/setup-ruby@v1
96104
with:
97105
ruby-version: ${{ matrix.ruby-version }}
98-
bundler-cache: true
106+
bundler-cache: ${{ matrix.ruby-version != '3.1' && matrix.ruby-version != '3.2' }}
107+
108+
- name: Load tool versions
109+
if: matrix.ruby-version == '3.1' || matrix.ruby-version == '3.2' || matrix.variant != 'default'
110+
run: grep -E '^[A-Z_]+=' scripts/tool-versions.env >> "$GITHUB_ENV"
111+
112+
- uses: sqlc-dev/setup-sqlc@v5
113+
if: matrix.ruby-version == '3.1' || matrix.ruby-version == '3.2' || matrix.variant != 'default'
114+
with:
115+
sqlc-version: '${{ env.SQLC_VERSION }}'
116+
117+
- name: Generate version-specific examples
118+
if: matrix.ruby-version == '3.1' || matrix.ruby-version == '3.2'
119+
run: |
120+
ruby scripts/tests/generate_examples.rb "${{ matrix.ruby-version }}" sqlc.local.yaml --generate-gemfile
121+
echo "EXAMPLES_DIR=$PWD/.examples-ruby-${{ matrix.ruby-version }}" >> "$GITHUB_ENV"
122+
123+
- name: Generate option variant
124+
if: matrix.variant == 'module-no-prepared'
125+
run: |
126+
ruby scripts/tests/generate_examples.rb 4.0 sqlc.local.yaml --driver pg --options '{"moduleName":"MyApp::Db","preparedStatements":false}'
127+
echo "EXAMPLES_DIR=$PWD/.examples-ruby-4.0" >> "$GITHUB_ENV"
128+
129+
- name: Install E2E dependencies
130+
if: matrix.ruby-version == '3.1' || matrix.ruby-version == '3.2'
131+
run: bundle install
99132

100133
- name: Create the schema
101134
run: psql -v ON_ERROR_STOP=1 -h 127.0.0.1 -U "${DB_USER}" -d "${DB_NAME}" -f examples/authors/postgresql/schema.sql
@@ -106,13 +139,17 @@ jobs:
106139
run: bundle exec rake end2end_pg
107140

108141
end2end-mysql:
109-
name: End-to-End (MySQL, Ruby ${{ matrix.ruby-version }})
142+
name: End-to-End (MySQL, Ruby ${{ matrix.ruby-version }}, ${{ matrix.variant }})
110143
runs-on: ubuntu-latest
111144

112145
strategy:
113146
fail-fast: false
114147
matrix:
115-
ruby-version: ['3.3', '4.0']
148+
ruby-version: ['3.1', '3.2', '3.3', '3.4', '4.0']
149+
variant: ['default']
150+
include:
151+
- ruby-version: '4.0'
152+
variant: 'module-name'
116153

117154
services:
118155
mysql:
@@ -130,14 +167,42 @@ jobs:
130167
131168
env:
132169
MYSQL_HOST: 127.0.0.1
170+
EXAMPLES_DRIVER: mysql2
171+
EXAMPLES_MODULE: ${{ matrix.variant == 'module-name' && 'MyApp::Db' || 'Mysql2Codegen' }}
172+
BUNDLE_GEMFILE: ${{ (matrix.ruby-version == '3.1' || matrix.ruby-version == '3.2') && 'Gemfile.e2e' || 'Gemfile' }}
133173

134174
steps:
135175
- uses: actions/checkout@v7
136176

137177
- uses: ruby/setup-ruby@v1
138178
with:
139179
ruby-version: ${{ matrix.ruby-version }}
140-
bundler-cache: true
180+
bundler-cache: ${{ matrix.ruby-version != '3.1' && matrix.ruby-version != '3.2' }}
181+
182+
- name: Load tool versions
183+
if: matrix.ruby-version == '3.1' || matrix.ruby-version == '3.2' || matrix.variant != 'default'
184+
run: grep -E '^[A-Z_]+=' scripts/tool-versions.env >> "$GITHUB_ENV"
185+
186+
- uses: sqlc-dev/setup-sqlc@v5
187+
if: matrix.ruby-version == '3.1' || matrix.ruby-version == '3.2' || matrix.variant != 'default'
188+
with:
189+
sqlc-version: '${{ env.SQLC_VERSION }}'
190+
191+
- name: Generate version-specific examples
192+
if: matrix.ruby-version == '3.1' || matrix.ruby-version == '3.2'
193+
run: |
194+
ruby scripts/tests/generate_examples.rb "${{ matrix.ruby-version }}" sqlc.local.yaml --generate-gemfile
195+
echo "EXAMPLES_DIR=$PWD/.examples-ruby-${{ matrix.ruby-version }}" >> "$GITHUB_ENV"
196+
197+
- name: Generate option variant
198+
if: matrix.variant == 'module-name'
199+
run: |
200+
ruby scripts/tests/generate_examples.rb 4.0 sqlc.local.yaml --driver mysql2 --options '{"moduleName":"MyApp::Db"}'
201+
echo "EXAMPLES_DIR=$PWD/.examples-ruby-4.0" >> "$GITHUB_ENV"
202+
203+
- name: Install E2E dependencies
204+
if: matrix.ruby-version == '3.1' || matrix.ruby-version == '3.2'
205+
run: bundle install
141206

142207
- name: Create the schema (and allow LOAD DATA LOCAL INFILE for :copyfrom)
143208
run: |
@@ -148,21 +213,104 @@ jobs:
148213
run: bundle exec rake end2end_mysql2
149214

150215
end2end-sqlite:
151-
name: End-to-End (SQLite, Ruby ${{ matrix.ruby-version }})
216+
name: End-to-End (SQLite, Ruby ${{ matrix.ruby-version }}, ${{ matrix.variant }})
152217
runs-on: ubuntu-latest
153218

154219
strategy:
155220
fail-fast: false
156221
matrix:
157-
ruby-version: ['3.3', '4.0']
222+
ruby-version: ['3.1', '3.2', '3.3', '3.4', '4.0']
223+
variant: ['default']
224+
include:
225+
- ruby-version: '4.0'
226+
variant: 'module-name'
227+
228+
env:
229+
EXAMPLES_DRIVER: sqlite3
230+
EXAMPLES_MODULE: ${{ matrix.variant == 'module-name' && 'MyApp::Db' || 'Sqlite3Codegen' }}
231+
BUNDLE_GEMFILE: ${{ (matrix.ruby-version == '3.1' || matrix.ruby-version == '3.2') && 'Gemfile.e2e' || 'Gemfile' }}
158232

159233
steps:
160234
- uses: actions/checkout@v7
161235

162236
- uses: ruby/setup-ruby@v1
163237
with:
164238
ruby-version: ${{ matrix.ruby-version }}
165-
bundler-cache: true
239+
bundler-cache: ${{ matrix.ruby-version != '3.1' && matrix.ruby-version != '3.2' }}
240+
241+
- name: Load tool versions
242+
if: matrix.ruby-version == '3.1' || matrix.ruby-version == '3.2' || matrix.variant != 'default'
243+
run: grep -E '^[A-Z_]+=' scripts/tool-versions.env >> "$GITHUB_ENV"
244+
245+
- uses: sqlc-dev/setup-sqlc@v5
246+
if: matrix.ruby-version == '3.1' || matrix.ruby-version == '3.2' || matrix.variant != 'default'
247+
with:
248+
sqlc-version: '${{ env.SQLC_VERSION }}'
249+
250+
- name: Generate version-specific examples
251+
if: matrix.ruby-version == '3.1' || matrix.ruby-version == '3.2'
252+
run: |
253+
ruby scripts/tests/generate_examples.rb "${{ matrix.ruby-version }}" sqlc.local.yaml --generate-gemfile
254+
echo "EXAMPLES_DIR=$PWD/.examples-ruby-${{ matrix.ruby-version }}" >> "$GITHUB_ENV"
255+
256+
- name: Generate option variant
257+
if: matrix.variant == 'module-name'
258+
run: |
259+
ruby scripts/tests/generate_examples.rb 4.0 sqlc.local.yaml --driver sqlite3 --options '{"moduleName":"MyApp::Db"}'
260+
echo "EXAMPLES_DIR=$PWD/.examples-ruby-4.0" >> "$GITHUB_ENV"
261+
262+
- name: Install E2E dependencies
263+
if: matrix.ruby-version == '3.1' || matrix.ruby-version == '3.2'
264+
run: bundle install
166265

167266
- name: End-to-End tests
168267
run: bundle exec rake end2end_sqlite3
268+
269+
end2end-options:
270+
name: Generator options E2E (Ruby ${{ matrix.ruby-version }})
271+
runs-on: ubuntu-latest
272+
273+
strategy:
274+
fail-fast: false
275+
matrix:
276+
ruby-version: ['3.1', '4.0']
277+
278+
services:
279+
postgres:
280+
image: postgres:16.2
281+
env:
282+
POSTGRES_DB: tests
283+
POSTGRES_USER: root
284+
POSTGRES_PASSWORD: pass
285+
ports:
286+
- 5432:5432
287+
options: >-
288+
--health-cmd "pg_isready -U root -d tests"
289+
--health-interval 5s
290+
--health-timeout 5s
291+
--health-retries 10
292+
293+
env:
294+
POSTGRES_HOST: 127.0.0.1
295+
BUNDLE_GEMFILE: Gemfile.options.e2e
296+
297+
steps:
298+
- uses: actions/checkout@v7
299+
300+
- uses: ruby/setup-ruby@v1
301+
with:
302+
ruby-version: ${{ matrix.ruby-version }}
303+
bundler-cache: false
304+
305+
- name: Install options test dependencies
306+
run: bundle install
307+
308+
- name: Load tool versions
309+
run: grep -E '^[A-Z_]+=' scripts/tool-versions.env >> "$GITHUB_ENV"
310+
311+
- uses: sqlc-dev/setup-sqlc@v5
312+
with:
313+
sqlc-version: '${{ env.SQLC_VERSION }}'
314+
315+
- name: End-to-end option tests
316+
run: bundle exec ruby tests/end2end_options.rb

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,3 +144,4 @@ plugin.wasm
144144
plugins
145145
# scratch output of scripts/tests/run_codegen.rb
146146
.codegen-test*
147+
.examples-ruby-*

‎CLAUDE.md‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,21 @@ UPDATE_GOLDEN=1 bundle exec ruby -Itest test/extended_golden_test.rb # rewrite
3131
* **Generated code must stay valid for Ruby 3.1–4.0** (`Struct` below 3.2, `Data` from 3.2) and RuboCop/Steep-clean.
3232
* Generated code is plain, idiomatic Ruby (keyword args, `Data` rows, implicit returns, 2-space indent); do not mirror
3333
the C# sibling plugin's style. Parameter *values* are never logged.
34-
* Prepared statements are per connection (`ConnectionState`) because the query object is shared by pooled connections.
34+
* PostgreSQL prepared statements are per connection (`ConnectionState`) because the query object is shared by pooled
35+
connections. MySQL uses client-side quoting and `Mysql2::Client#query` instead of server-side prepared statements.
36+
* Every README claim or supported feature needs a real-database E2E test for each applicable engine, listed in
37+
`docs/Coverage.md`. A bug fix starts with an E2E test that fails before the fix; use unit tests only where E2E cannot
38+
reach the behavior (for example option validation or generation errors).
39+
* E2E coverage runs on every supported Ruby and includes full-suite option variants. Update `docs/Coverage.md` and
40+
`docs/Testing.md` with new supported behavior and its test names.
3541
* sqlc runs process plugins with an empty env (`env: [PATH]` is needed in `sqlc.local.yaml`) and resolves `out:`
3642
relative to the config file.
3743

3844
## Git, CI and releases
3945
* Develop on a feature branch, small commits; PRs target `main`. Label PRs (`bug`, `enhancement`, `documentation`; `breaking` for incompatible changes, see `.github/release.yml`).
40-
* CI: `build.yml` (WASM, lint, `sqlc diff`, Steep, option matrix) and `tests.yml` (unit, Ruby 3.1/3.2/3.4/4.0, E2E on real
41-
PostgreSQL/MySQL/SQLite). Both must be green.
46+
* CI: `build.yml` (WASM, lint, `sqlc diff`, Steep, option matrix) and `tests.yml` (unit, compatibility Ruby
47+
3.1/3.2/3.4/4.0, full E2E Ruby 3.1–4.0, Ruby 4.0 module-name variants and PostgreSQL without prepared statements,
48+
plus generator-options E2E on Ruby 3.1/4.0 against PostgreSQL 16, MySQL 8.3 and SQLite). Both must be green.
4249
* **Never create tags or releases by hand and never add release markers to commit messages.** Releases are started by a
4350
maintainer with the *Release* workflow (`docs/Releasing.md`); do not trigger it unless explicitly asked.
4451
* Tool versions (sqlc, ruby.wasm) are pinned in `scripts/tool-versions.env`; bump them there only.

‎Gemfile.e2e‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# frozen_string_literal: true
2+
3+
source 'https://rubygems.org'
4+
5+
examples_dir = ENV.fetch('EXAMPLES_DIR') { raise 'EXAMPLES_DIR must point at generated scratch examples' }
6+
driver = ENV.fetch('EXAMPLES_DRIVER') { raise 'EXAMPLES_DRIVER must be set for E2E bundling' }
7+
eval_gemfile File.join(examples_dir, driver, 'Gemfile')
8+
9+
gem 'async', RUBY_VERSION.start_with?('3.1') ? '< 2.7' : '>= 2.7'
10+
gem 'minitest'
11+
gem 'rake'

‎Gemfile.options.e2e‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
source 'https://rubygems.org'
2+
3+
gem 'connection_pool', '~> 2.5'
4+
gem 'minitest', RUBY_VERSION.start_with?('3.1') ? '< 6' : '>= 5'
5+
gem 'pg', '1.7.0'
6+
gem 'sqlite3'

‎README.md‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -93,15 +93,18 @@ per table, one module of constants per enum), `connection.rb` (shared helpers) a
9393
* **Arguments** are keywords named after the parameters (`get_author(id:)`); `sqlc.arg(name)` names them yourself.
9494
Missing or unknown ones raise `ArgumentError`. Nullable parameters named with `sqlc.arg` / `sqlc.narg` default
9595
to `nil`; other nullable parameters (`VALUES ($1, $2)`) must be passed, even as `nil`.
96-
* **Rows** are frozen `Data` objects (keyword `Struct`s below Ruby 3.2), so pattern matching works: `case row in { id:, name: }`.
96+
* **Rows** are frozen `Data` objects from Ruby 3.2 (with `with` and `to_h`) or mutable keyword `Struct`s below Ruby 3.2;
97+
both support pattern matching: `case row in { id:, name: }`.
9798
* **Bang finders:** every `:one` query also gets a `get_author!` that raises `QuerySql::NotFound` instead of returning `nil`.
9899
* **Connections:** `QuerySql.connect(params, **pool_options)` builds a [`connection_pool`](https://github.com/mperham/connection_pool).
99100
To use a pool you already have (or a fake in tests) pass it to `QuerySql.new(pool)`; anything with `#with` works.
100101
For SQLite pass a `SQLite3::Database`: `QuerySql.new(db)`.
101102
* **Logging:** `connect(params, logger: Rails.logger)` / `new(pool, logger:)` logs `QuerySql#get_author (0.4ms)` at
102103
debug level for each query and transaction. Parameter values are never logged.
103104
* **Async / fibers:** it is plain synchronous Ruby and works with the Fiber scheduler ([`async`](https://github.com/socketry/async)):
104-
inside `Sync { ... }`, pooled `pg` and `mysql2` queries run concurrently. SQLite queries run one at a time.
105+
inside `Sync { ... }`, pooled `pg` and `mysql2` queries run concurrently. MySQL parameters are quoted client-side
106+
with `Mysql2::Client#escape` and sent with `Client#query`, not server-side prepared statements. SQLite queries run
107+
one at a time.
105108
* **Style:** SQL lives in frozen heredoc constants (`GET_AUTHOR_SQL`), comments above a query become its doc comment,
106109
table / column / enum comments of the schema become doc comments of the models. The code is RuboCop-clean; where a
107110
name from your schema breaks a RuboCop naming rule (`"UserId"`, `naïve`), that class or method gets a `rubocop:disable`.
@@ -115,7 +118,11 @@ queries.transaction(isolation: :serializable) do |tx|
115118
end
116119
```
117120
* Everything in the block runs on one connection. It commits when the block ends (also on `break`, `return`, `throw`)
118-
and rolls back when it raises or the thread is killed. A nested `transaction` rolls back only its own part.
121+
and rolls back when it raises or the thread is killed. On Ruby <3.3 with timeout <0.4, `break`, `return`, and
122+
`throw` also roll back because Timeout cannot be told apart; add `gem 'timeout', '>= 0.4'` to the generated Gemfile
123+
to keep those exits committing. A nested `transaction` rolls back only its own part. With `connection_pool` or
124+
SQLite, parent-object calls from the same thread reuse the transaction connection; injected `#with` objects must do
125+
the same.
119126
* `isolation:` (`pg`, `mysql2`) takes `:read_uncommitted`, `:read_committed`, `:repeatable_read`, `:serializable`;
120127
`mode:` (`sqlite3`) takes `:deferred`, `:immediate`, `:exclusive`. Other values raise before anything runs, and so
121128
do `isolation:` / `mode:` on a nested `transaction` (a savepoint cannot change them).
@@ -170,7 +177,11 @@ server; duplicate keys and invalid values raise `Mysql2::Error` instead of being
170177
The generated SQLite code uses `Monitor`: if you run Steep, add `library "monitor"` to your `Steepfile`.
171178

172179
### Names
173-
* Names are snake_cased, acronyms kept together (`MIN_ID` → `min_id`, `HTTPServer` → `http_server`). Ruby keywords and names a row or method already uses get a trailing `_` (`class_`, `hash_`).
180+
* Query methods and keyword arguments are snake_cased, with acronyms kept together (`MIN_ID` → `min_id`,
181+
`HTTPServer` → `http_server`); Ruby keywords get a trailing `_` (`end_:`). Row members use the column spelling
182+
reported by sqlc for the engine, except names that conflict with generated row methods (`class_`, `hash_`):
183+
PostgreSQL and SQLite keep `"camelCase"` as `:camelCase`, while MySQL reports it as `:camelcase`. A column named
184+
`end` is the row member `:end` but the argument `end_:`.
174185
* A parameter used twice is one keyword when named with `sqlc.arg`; repeated `?` / `$n` of one column become `id:`, `id_2:`.
175186
* A table `authors` next to a table `author` keeps its plural model name (`Authors`). Query names that would replace
176187
a generated method (`Transaction`, `Initialize`, ...) are errors.
@@ -179,8 +190,8 @@ server; duplicate keys and invalid values raise `Mysql2::Error` instead of being
179190
* Two result columns with the same name (e.g. `a.id, b.id`) are an error: alias one (`b.id AS book_id`) or use `sqlc.embed`.
180191
* SQLite's `NUMERIC` affinity can return an `Integer` where `Float` is declared.
181192
* `:batchexec` / `:batchone` / `:batchmany` are not atomic on their own: wrap them in `transaction` for all-or-nothing.
182-
* SQLite: a transaction belongs to the thread that opened it; a Fiber / `Enumerator#next` inside it that uses the same
183-
database waits for it (with `async`, run the work in the transaction's own fiber).
193+
* SQLite transactions belong to the thread that opened them; fibers sharing the same database take turns, and a
194+
transaction holds it until it ends.
184195
* Not applicable to Ruby (they exist in the C# plugin): `withAsyncSuffix` / `withCancellationToken` (use the Fiber
185196
scheduler), `useDapper`, target framework / csproj options (`moduleName` replaces the namespace).
186197

‎docs/Architecture.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ stdout ◄─ Proto (encode) ◄─ GenerateResponse (query_sql.rb, query_sql.rb
2727
| `type_resolver.rb` | RBS type of a column / parameter: driver type table, arrays, nullability (`T?`), `overrides:` (a `db_type` override types array elements too) |
2828
| `catalog.rb` | the schema's tables and enums, and their Ruby names |
2929
| `drivers/base.rb` | the driver interface and what all drivers share: `instrument` logging, `NotFound`, transaction RBS |
30-
| `drivers/{pg,mysql2,sqlite3}.rb` | the per-library parts: type mapping, connecting / pooling, preparing and executing statements, transactions, `:copyfrom` |
30+
| `drivers/{pg,mysql2,sqlite3}.rb` | the per-library parts: type mapping, connecting / pooling, executing statements, transactions, `:copyfrom` |
3131
| `code.rb` | text helpers: indentation, `snake_case`, `camelize`, Ruby-keyword-safe parameter names, `rubocop:disable` pairs for schema names that break a naming cop |
3232

3333
**Rule of thumb:** `MethodGen` / `Generator` decide *what* is generated and are the same for every database; a driver only
@@ -62,11 +62,13 @@ Look at [`examples/pg/query_sql.rb`](../examples/pg/query_sql.rb) for a complete
6262
6363
Design decisions worth knowing (the *why* is in the comments of `drivers/base.rb` and `drivers/pg.rb`):
6464
65-
* **Prepared statements are per connection.** A pooled query object is shared by many connections, and a prepared
66-
statement exists only on the connection that prepared it, so each connection remembers its own (`ConnectionState`).
65+
* **PostgreSQL prepared statements are per connection.** A pooled query object is shared by many connections, and a
66+
prepared statement exists only on the connection that prepared it, so each connection remembers its own
67+
(`ConnectionState`). MySQL quotes values client-side and uses `Mysql2::Client#query` so queries cooperate with the
68+
Fiber scheduler.
6769
* **Pool injection.** `QuerySql.new(pool)` accepts anything that responds to `#with`, so an app can share its pool
6870
and tests can pass a fake. `connect(...)` is only a convenience that builds a `connection_pool`.
69-
* **Statements are closed.** SQLite/MySQL statements are closed in `ensure` (an open SQLite statement blocks `COMMIT`).
71+
* **SQLite statements are closed.** They are closed in `ensure` because an open statement blocks `COMMIT`.
7072
* **Parameters are encoded by the driver.** `Driver#encode_param` (e.g. `bytea`, `json` and arrays on `pg`) is used by
7173
every command, batches included; add a type's encoding there, not in `MethodGen`.
7274
* **`:copyfrom` is all or nothing** on every driver (a savepoint / transaction around the load), and MySQL's

0 commit comments

Comments
 (0)