skyward-orm 0.2.0 → 0.3.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.
Files changed (191) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +182 -75
  3. data/lib/skyward/orm/adapters/postgresql/connection.rb +52 -0
  4. data/lib/skyward/orm/adapters/postgresql.rb +283 -0
  5. data/lib/skyward/orm/adapters/sqlite/constraints.rb +172 -0
  6. data/lib/skyward/orm/adapters/sqlite.rb +317 -0
  7. data/lib/skyward/orm/adapters.rb +38 -0
  8. data/lib/skyward/orm/catalog/column.rb +12 -0
  9. data/lib/skyward/orm/catalog/constraint.rb +13 -0
  10. data/lib/skyward/orm/catalog/index.rb +11 -0
  11. data/lib/skyward/orm/catalog/table.rb +10 -0
  12. data/lib/skyward/orm/catalog.rb +6 -0
  13. data/lib/skyward/orm/cli/boot_file.rb +43 -0
  14. data/lib/skyward/orm/cli/migrate.rb +30 -0
  15. data/lib/skyward/orm/cli/migration.rb +111 -0
  16. data/lib/skyward/orm/cli/rollback.rb +18 -0
  17. data/lib/skyward/orm/cli/status.rb +36 -0
  18. data/lib/skyward/orm/cli.rb +4 -0
  19. data/lib/skyward/orm/commands.rb +64 -0
  20. data/lib/skyward/orm/connection/database/schema_check.rb +67 -0
  21. data/lib/skyward/orm/connection/database.rb +357 -0
  22. data/lib/skyward/orm/connection/pool.rb +102 -0
  23. data/lib/skyward/orm/connection/session.rb +38 -0
  24. data/lib/skyward/orm/connection.rb +7 -0
  25. data/lib/skyward/orm/members.rb +16 -0
  26. data/lib/skyward/orm/migration_error.rb +4 -0
  27. data/lib/skyward/orm/migrations/add_column.rb +7 -0
  28. data/lib/skyward/orm/migrations/add_constraint.rb +7 -0
  29. data/lib/skyward/orm/migrations/add_index.rb +7 -0
  30. data/lib/skyward/orm/migrations/alter_table.rb +12 -0
  31. data/lib/skyward/orm/migrations/change_default.rb +9 -0
  32. data/lib/skyward/orm/migrations/change_nullable.rb +8 -0
  33. data/lib/skyward/orm/migrations/change_type.rb +9 -0
  34. data/lib/skyward/orm/migrations/create_table.rb +8 -0
  35. data/lib/skyward/orm/migrations/definitions.rb +176 -0
  36. data/lib/skyward/orm/migrations/diff.rb +213 -0
  37. data/lib/skyward/orm/migrations/directory.rb +48 -0
  38. data/lib/skyward/orm/migrations/discovery.rb +14 -0
  39. data/lib/skyward/orm/migrations/drop_column.rb +7 -0
  40. data/lib/skyward/orm/migrations/drop_constraint.rb +7 -0
  41. data/lib/skyward/orm/migrations/drop_index.rb +7 -0
  42. data/lib/skyward/orm/migrations/rename_column.rb +8 -0
  43. data/lib/skyward/orm/migrations/runner/edited.rb +7 -0
  44. data/lib/skyward/orm/migrations/runner/failed.rb +8 -0
  45. data/lib/skyward/orm/migrations/runner/irreversible.rb +7 -0
  46. data/lib/skyward/orm/migrations/runner/locked.rb +8 -0
  47. data/lib/skyward/orm/migrations/runner/migration.rb +11 -0
  48. data/lib/skyward/orm/migrations/runner/missing.rb +7 -0
  49. data/lib/skyward/orm/migrations/runner/raced.rb +7 -0
  50. data/lib/skyward/orm/migrations/runner.rb +227 -0
  51. data/lib/skyward/orm/migrations/script.rb +350 -0
  52. data/lib/skyward/orm/migrations/status.rb +93 -0
  53. data/lib/skyward/orm/migrations/summary.rb +110 -0
  54. data/lib/skyward/orm/migrations/versions.rb +19 -0
  55. data/lib/skyward/orm/migrations.rb +8 -0
  56. data/lib/skyward/orm/placeholders.rb +37 -0
  57. data/lib/skyward/orm/pool_timeout.rb +4 -0
  58. data/lib/skyward/orm/projection.rb +67 -0
  59. data/lib/skyward/orm/queries/clauses.rb +588 -0
  60. data/lib/skyward/orm/queries.rb +4 -0
  61. data/lib/skyward/orm/query.rb +26 -0
  62. data/lib/skyward/orm/record.rb +96 -0
  63. data/lib/skyward/orm/schema_mismatch.rb +4 -0
  64. data/lib/skyward/orm/statements.rb +97 -0
  65. data/lib/skyward/orm/tables/check.rb +8 -0
  66. data/lib/skyward/orm/tables/column.rb +10 -0
  67. data/lib/skyward/orm/tables/column_types.rb +74 -0
  68. data/lib/skyward/orm/tables/declarations.rb +172 -0
  69. data/lib/skyward/orm/tables/length.rb +8 -0
  70. data/lib/skyward/orm/tables/loaded.rb +21 -0
  71. data/lib/skyward/orm/tables/reference.rb +9 -0
  72. data/lib/skyward/orm/tables/rows.rb +52 -0
  73. data/lib/skyward/orm/tables/schema.rb +14 -0
  74. data/lib/skyward/orm/tables/sql.rb +7 -0
  75. data/lib/skyward/orm/tables/validation.rb +29 -0
  76. data/lib/skyward/orm/tables/values.rb +102 -0
  77. data/lib/skyward/orm/tables.rb +7 -0
  78. data/lib/skyward/orm/transactional.rb +18 -0
  79. data/lib/skyward/orm/version.rb +1 -1
  80. data/lib/skyward/orm/violation.rb +13 -0
  81. data/lib/skyward/orm/violation_error.rb +13 -0
  82. data/lib/skyward/orm.rb +72 -1
  83. data/sig/generated/skyward/orm/adapters/postgresql/connection.rbs +41 -0
  84. data/sig/generated/skyward/orm/adapters/postgresql.rbs +138 -0
  85. data/sig/generated/skyward/orm/adapters/sqlite/constraints.rbs +87 -0
  86. data/sig/generated/skyward/orm/adapters/sqlite.rbs +166 -0
  87. data/sig/generated/skyward/orm/adapters.rbs +15 -0
  88. data/sig/generated/skyward/orm/catalog/column.rbs +20 -0
  89. data/sig/generated/skyward/orm/catalog/constraint.rbs +22 -0
  90. data/sig/generated/skyward/orm/catalog/index.rbs +20 -0
  91. data/sig/generated/skyward/orm/catalog/table.rbs +20 -0
  92. data/sig/generated/skyward/orm/catalog.rbs +5 -0
  93. data/sig/generated/skyward/orm/cli/boot_file.rbs +21 -0
  94. data/sig/generated/skyward/orm/cli/migrate.rbs +15 -0
  95. data/sig/generated/skyward/orm/cli/migration.rbs +45 -0
  96. data/sig/generated/skyward/orm/cli/rollback.rbs +7 -0
  97. data/sig/generated/skyward/orm/cli/status.rbs +17 -0
  98. data/sig/generated/skyward/orm/cli.rbs +4 -0
  99. data/sig/generated/skyward/orm/commands.rbs +2 -0
  100. data/sig/generated/skyward/orm/connection/database/schema_check.rbs +31 -0
  101. data/sig/generated/skyward/orm/connection/database.rbs +226 -0
  102. data/sig/generated/skyward/orm/connection/pool.rbs +54 -0
  103. data/sig/generated/skyward/orm/connection/session.rbs +25 -0
  104. data/sig/generated/skyward/orm/connection.rbs +7 -0
  105. data/sig/generated/skyward/orm/members.rbs +9 -0
  106. data/sig/generated/skyward/orm/migration_error.rbs +4 -0
  107. data/sig/generated/skyward/orm/migrations/add_column.rbs +14 -0
  108. data/sig/generated/skyward/orm/migrations/add_constraint.rbs +14 -0
  109. data/sig/generated/skyward/orm/migrations/add_index.rbs +14 -0
  110. data/sig/generated/skyward/orm/migrations/alter_table.rbs +22 -0
  111. data/sig/generated/skyward/orm/migrations/change_default.rbs +18 -0
  112. data/sig/generated/skyward/orm/migrations/change_nullable.rbs +16 -0
  113. data/sig/generated/skyward/orm/migrations/change_type.rbs +18 -0
  114. data/sig/generated/skyward/orm/migrations/create_table.rbs +16 -0
  115. data/sig/generated/skyward/orm/migrations/definitions.rbs +81 -0
  116. data/sig/generated/skyward/orm/migrations/diff.rbs +99 -0
  117. data/sig/generated/skyward/orm/migrations/directory.rbs +37 -0
  118. data/sig/generated/skyward/orm/migrations/discovery.rbs +9 -0
  119. data/sig/generated/skyward/orm/migrations/drop_column.rbs +14 -0
  120. data/sig/generated/skyward/orm/migrations/drop_constraint.rbs +14 -0
  121. data/sig/generated/skyward/orm/migrations/drop_index.rbs +14 -0
  122. data/sig/generated/skyward/orm/migrations/rename_column.rbs +16 -0
  123. data/sig/generated/skyward/orm/migrations/runner/edited.rbs +14 -0
  124. data/sig/generated/skyward/orm/migrations/runner/failed.rbs +16 -0
  125. data/sig/generated/skyward/orm/migrations/runner/irreversible.rbs +14 -0
  126. data/sig/generated/skyward/orm/migrations/runner/locked.rbs +16 -0
  127. data/sig/generated/skyward/orm/migrations/runner/migration.rbs +22 -0
  128. data/sig/generated/skyward/orm/migrations/runner/missing.rbs +14 -0
  129. data/sig/generated/skyward/orm/migrations/runner/raced.rbs +14 -0
  130. data/sig/generated/skyward/orm/migrations/runner.rbs +73 -0
  131. data/sig/generated/skyward/orm/migrations/script.rbs +161 -0
  132. data/sig/generated/skyward/orm/migrations/status.rbs +49 -0
  133. data/sig/generated/skyward/orm/migrations/summary.rbs +50 -0
  134. data/sig/generated/skyward/orm/migrations/versions.rbs +11 -0
  135. data/sig/generated/skyward/orm/migrations.rbs +7 -0
  136. data/sig/generated/skyward/orm/placeholders.rbs +21 -0
  137. data/sig/generated/skyward/orm/pool_timeout.rbs +4 -0
  138. data/sig/generated/skyward/orm/projection.rbs +42 -0
  139. data/sig/generated/skyward/orm/queries/clauses.rbs +367 -0
  140. data/sig/generated/skyward/orm/queries.rbs +4 -0
  141. data/sig/generated/skyward/orm/query.rbs +20 -0
  142. data/sig/generated/skyward/orm/record.rbs +80 -0
  143. data/sig/generated/skyward/orm/schema_mismatch.rbs +4 -0
  144. data/sig/generated/skyward/orm/statements.rbs +53 -0
  145. data/sig/generated/skyward/orm/tables/check.rbs +16 -0
  146. data/sig/generated/skyward/orm/tables/column.rbs +20 -0
  147. data/sig/generated/skyward/orm/tables/column_types.rbs +39 -0
  148. data/sig/generated/skyward/orm/tables/declarations.rbs +87 -0
  149. data/sig/generated/skyward/orm/tables/length.rbs +16 -0
  150. data/sig/generated/skyward/orm/tables/loaded.rbs +14 -0
  151. data/sig/generated/skyward/orm/tables/reference.rbs +18 -0
  152. data/sig/generated/skyward/orm/tables/rows.rbs +24 -0
  153. data/sig/generated/skyward/orm/tables/schema.rbs +28 -0
  154. data/sig/generated/skyward/orm/tables/sql.rbs +14 -0
  155. data/sig/generated/skyward/orm/tables/validation.rbs +9 -0
  156. data/sig/generated/skyward/orm/tables/values.rbs +49 -0
  157. data/sig/generated/skyward/orm/tables.rbs +7 -0
  158. data/sig/generated/skyward/orm/transactional.rbs +11 -0
  159. data/sig/generated/skyward/orm/violation.rbs +22 -0
  160. data/sig/generated/skyward/orm/violation_error.rbs +10 -0
  161. data/sig/generated/skyward/orm.rbs +29 -0
  162. data/sig/manual/pg.rbs +31 -0
  163. data/sig/manual/skyward/orm/adapters/postgresql.rbs +3 -0
  164. data/sig/manual/skyward/orm/adapters/sqlite/constraints.rbs +3 -0
  165. data/sig/manual/skyward/orm/adapters/sqlite.rbs +3 -0
  166. data/sig/manual/skyward/orm/adapters.rbs +3 -0
  167. data/sig/manual/skyward/orm/cli/boot_file.rbs +3 -0
  168. data/sig/manual/skyward/orm/cli/migrate.rbs +3 -0
  169. data/sig/manual/skyward/orm/cli/migration.rbs +3 -0
  170. data/sig/manual/skyward/orm/cli/rollback.rbs +3 -0
  171. data/sig/manual/skyward/orm/cli/status.rbs +3 -0
  172. data/sig/manual/skyward/orm/connection/database/schema_check.rbs +3 -0
  173. data/sig/manual/skyward/orm/members.rbs +3 -0
  174. data/sig/manual/skyward/orm/migrations/definitions.rbs +3 -0
  175. data/sig/manual/skyward/orm/migrations/diff.rbs +3 -0
  176. data/sig/manual/skyward/orm/migrations/directory.rbs +3 -0
  177. data/sig/manual/skyward/orm/migrations/discovery.rbs +3 -0
  178. data/sig/manual/skyward/orm/migrations/runner.rbs +3 -0
  179. data/sig/manual/skyward/orm/migrations/script.rbs +3 -0
  180. data/sig/manual/skyward/orm/migrations/status.rbs +3 -0
  181. data/sig/manual/skyward/orm/migrations/summary.rbs +3 -0
  182. data/sig/manual/skyward/orm/migrations/versions.rbs +3 -0
  183. data/sig/manual/skyward/orm/placeholders.rbs +3 -0
  184. data/sig/manual/skyward/orm/statements.rbs +3 -0
  185. data/sig/manual/skyward/orm/tables/loaded.rbs +3 -0
  186. data/sig/manual/skyward/orm/tables/rows.rbs +3 -0
  187. data/sig/manual/skyward/orm/tables/validation.rbs +3 -0
  188. data/sig/manual/skyward/orm/tables/values.rbs +3 -0
  189. data/sig/manual/skyward/orm.rbs +45 -0
  190. data/sig/manual/sqlite3.rbs +23 -0
  191. metadata +188 -3
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c65065a6d2f559ecea6fb3f0842bfaa2759372e1ba7112e23518f8742dda2fc5
4
- data.tar.gz: 56fecc63feb4be7e7232475157c5ec51505a4d03acfe58774de24eb5f80dac4c
3
+ metadata.gz: da9c4c9d04d515636d88599dbd1e2473dcc1c7d578b37fb69749e6bcdf434b31
4
+ data.tar.gz: e0c7423070e0c97c72ad8bedfd68ca43190fc6cef28484a2410c1186338ba089
5
5
  SHA512:
6
- metadata.gz: 7583828cd595bd8d0be5f0616fb084c730ce0562825a1dff59fcd8f11828b510c8439bce211358f6811bf7ed7c766b3b98fdf0c69cab29e83e8a72cd7ded3d3f
7
- data.tar.gz: a38739f4b1689f20950a5ba8f64b81d13aeb55ef0c2df694184b21da1e997973358de16b881f8f731bb70e21a25cc29a6f5dd688419662330f7e906ebf5f7e1c
6
+ metadata.gz: 10e4ececfc63ed9c510e5da1474979efa215cde42f0bed4df411db93fb9de9822ec0f0b02a4f3173c9c1f468dcfb21f59f8cd68c079783424b6e8baf644b1621
7
+ data.tar.gz: e4eabc27e0f862ce2a5314ac73d8433b0e4c85f7e1c9d8d6199f675b2bb14cd590c72242608b418afae1fa5631b8150949fda08b1e00019ece66926e1267d283
data/README.md CHANGED
@@ -1,13 +1,13 @@
1
1
  # Skyward ORM
2
2
 
3
3
  > [!CAUTION]
4
- > **Work in progress: Skyward ORM doesn't do anything yet.** Version 0.1 is a skeleton. The gems install and load, but none of the features described here are built. This README is the spec for what's coming, not documentation of what exists. Don't depend on it yet.
4
+ > Skyward ORM is pre-1.0. This README is its spec, most of it is built, and [Status](#status) lists exactly what is. Any release may change the API, so don't run it in production yet.
5
5
 
6
- A small, fast Ruby ORM where **a class is a table and its rows are values**.
6
+ A Ruby ORM for PostgreSQL and SQLite where **a class is a table and its rows are values**.
7
7
 
8
- You write a plain Ruby class with a typed reader for each column, and tell Skyward ORM which table it lives in. The class is then the table: you query it, write to it and migrate it. What comes back are immutable instances of your class. There are no callbacks, no dirty tracking and no lazy loading. You get your data and the SQL that fetched it.
8
+ You write a plain Ruby class with a typed reader for each column, and tell Skyward ORM which table it lives in. From then on the class is the table: you query it and write to it, and Skyward ORM writes its migrations from it. Rows come back as frozen instances of your class. There are no callbacks, no dirty tracking and no lazy loading, so you get your data and the SQL that fetched it.
9
9
 
10
- Skyward ORM is half of Skyward. The other half is [Skyward API](../skyward-api/README.md), but each works without the other.
10
+ It's half of Skyward. The other half is [Skyward API](../skyward-api/README.md), and you can use either without the other.
11
11
 
12
12
  ```ruby
13
13
  # rbs_inline: enabled
@@ -25,14 +25,14 @@ end
25
25
 
26
26
  Skyward.connect("sqlite://todos.db")
27
27
 
28
- Todo.insert(title: "Buy milk")
28
+ Todo.into(Todo).insert(title: "Buy milk")
29
29
  # => #<Todo id=1, title="Buy milk", done=false>
30
30
 
31
31
  Todo.where(done: false).map(&:title)
32
32
  # => ["Buy milk"]
33
33
 
34
34
  Todo.where(id: 1).update(done: true)
35
- # => [#<Todo id=1, title="Buy milk", done=true>]
35
+ # => 1
36
36
  ```
37
37
 
38
38
  ```sh
@@ -57,7 +57,7 @@ $ skyward migrate
57
57
  - [Testing](#testing)
58
58
  - [Performance](#performance)
59
59
  - [CLI](#cli)
60
- - [Coming from…](#coming-from)
60
+ - [Coming from other libraries](#coming-from-other-libraries)
61
61
  - [Design principles](#design-principles)
62
62
  - [Status](#status)
63
63
 
@@ -140,10 +140,10 @@ Wrote db/migrate/20261018093000_create_todos.sql. Review it, then run `skyward m
140
140
  ```sql
141
141
  -- db/migrate/20261018093000_create_todos.sql
142
142
  CREATE TABLE todos (
143
- id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
144
- list_id bigint NOT NULL REFERENCES lists ON DELETE CASCADE,
145
- title text NOT NULL CHECK (length(title) BETWEEN 1 AND 200),
146
- priority text NOT NULL DEFAULT 'normal' CHECK (priority IN ('low', 'normal', 'high')),
143
+ id bigint GENERATED ALWAYS AS IDENTITY CONSTRAINT todos_pkey PRIMARY KEY,
144
+ list_id bigint NOT NULL CONSTRAINT todos_list_id_fkey REFERENCES lists ON DELETE CASCADE,
145
+ title text NOT NULL CONSTRAINT todos_title_check CHECK (length(title) BETWEEN 1 AND 200),
146
+ priority text NOT NULL DEFAULT 'normal' CONSTRAINT todos_priority_check CHECK (priority IN ('low', 'normal', 'high')),
147
147
  due_on date,
148
148
  done boolean NOT NULL DEFAULT false,
149
149
  created_at timestamptz NOT NULL DEFAULT now()
@@ -160,13 +160,53 @@ Later, add `:notes #: String?` to `Todo` and run it again:
160
160
  $ skyward migration add_notes_to_todos
161
161
  Todo differs from the todos table:
162
162
  + notes text NULL
163
- Wrote db/migrate/20261019141500_add_notes_to_todos.sql.
163
+ Wrote db/migrate/20261019141500_add_notes_to_todos.sql. Review it, then run `skyward migrate`.
164
164
  ```
165
165
 
166
+ ```sql
167
+ -- db/migrate/20261019141500_add_notes_to_todos.sql
168
+ ALTER TABLE todos ADD COLUMN notes text;
169
+
170
+ -- down
171
+ ALTER TABLE todos DROP COLUMN notes;
172
+ ```
173
+
174
+ Any other change to the class works the same way. Rename `notes` to `details`, make `due_on` a `Date`, and add `index :due_on`:
175
+
176
+ ```
177
+ $ skyward migration rework_todos
178
+ Did you rename todos.notes to todos.details? [y/N] y
179
+ Todo differs from the todos table:
180
+ ~ details renamed from notes
181
+ ~ due_on NOT NULL, was NULL
182
+ + todos_due_on_index index (due_on)
183
+ Wrote db/migrate/20261020110000_rework_todos.sql. Review it, then run `skyward migrate`.
184
+ ```
185
+
186
+ ```sql
187
+ -- db/migrate/20261020110000_rework_todos.sql
188
+ ALTER TABLE todos RENAME COLUMN notes TO details;
189
+ -- TODO: backfill the NULLs in todos.due_on before it becomes NOT NULL
190
+ ALTER TABLE todos ALTER COLUMN due_on SET NOT NULL;
191
+ CREATE INDEX todos_due_on_index ON todos (due_on);
192
+
193
+ -- down
194
+ DROP INDEX todos_due_on_index;
195
+ ALTER TABLE todos ALTER COLUMN due_on DROP NOT NULL;
196
+ ALTER TABLE todos RENAME COLUMN details TO notes;
197
+ ```
198
+
199
+ The summary marks what's added `+`, dropped `-` and changed `~`: columns, their types, `NULL`s and defaults, and indexes, uniques, checks and references.
200
+
201
+ - **Every constraint and index has a name.** It's the table, the columns and the kind, such as `todos_title_check`, so a [`Violation`](#when-the-database-says-no) names the same constraint on PostgreSQL and SQLite.
166
202
  - **Migrations are plain SQL files you commit.** Read them, edit them, and add data backfills to the same file. Skyward ORM runs each one once, in order, inside a transaction. `skyward rollback` runs the `-- down` section.
167
- - **Skyward ORM asks when it can't know what you meant.** If a column disappears and another appears, it asks whether you renamed it, rather than dropping your data.
203
+ - **Every change has a down.** A dropped column comes back in the down section with a comment that its data isn't restored, since dropping it lost that.
204
+ - **Skyward ORM asks when it can't know what you meant.** If a column disappears and another of a compatible type appears, it asks whether you renamed it, rather than dropping your data. Yes renames it, and no drops one and adds the other. With no terminal to ask, as in CI, it writes nothing, and names the columns to run it again for in a terminal.
168
205
  - **Generation needs types.** A column without a `#:` type still works at runtime, but Skyward ORM can't guess its SQL type. The migration gets `-- TODO: todos.notes needs a type`, and you write that line yourself.
169
206
  - **A new required column needs a default.** The rows already in the table need a value for it, so the migration gets `-- TODO: todos.notes needs a DEFAULT for the rows todos already has`. Give it one, or make the column nullable.
207
+ - **A column made required needs its `NULL`s filled.** The migration gets `-- TODO: backfill the NULLs in todos.due_on before it becomes NOT NULL`, where your `UPDATE` goes.
208
+ - **SQLite rebuilds a table to change it.** SQLite's `ALTER TABLE` adds, drops and renames columns, but can't change one or its constraints, so the migration creates the new table, copies the rows, drops the old table, renames the new one and recreates its indexes. Dropping a table runs the `ON DELETE` of every table that references it, and SQLite only turns foreign keys off outside a transaction, so `skyward migrate` and `skyward rollback` run each SQLite migration with `PRAGMA foreign_keys = OFF`, and check them with `PRAGMA foreign_key_check` before they commit. The rows that reference a rebuilt table stay as they were.
209
+ - **A table with no class is never dropped.** A class that isn't loaded looks the same as one that's gone, so `skyward status` reports the table instead.
170
210
  - **Hand-written migrations are always an option.** `skyward migration --empty backfill_priorities` gives you an empty file for SQL you write yourself.
171
211
 
172
212
  Business rules like the title length live in the database, where they hold for every writer, and they come back to Ruby as a [`Violation`](#when-the-database-says-no).
@@ -181,18 +221,20 @@ Skyward.connect(ENV.fetch("DATABASE_URL"), pool: 10)
181
221
 
182
222
  Call it once, where your app boots. Skyward ORM reads your column types from the `.rbs` files under `sig/`, or the directory you pass as `signatures:`.
183
223
 
184
- Like ActiveRecord, Skyward ORM keeps the connection for you, so `Todo.where(...)` just works. Also like ActiveRecord, it gives you the seams that make that safe: tests that each run in a rolled-back transaction, and `Skyward.using(other_database) { ... }` to switch databases for one block. The switch applies only to the current fiber, never globally.
224
+ Like ActiveRecord, Skyward ORM keeps the connection for you, so `Todo.where(...)` just works. It also gives you what makes that safe: tests that each run in a rolled-back transaction, and `Skyward.using(other_database) { ... }` to switch databases for one block. The switch applies only to the current fiber, never globally.
185
225
 
186
226
  When you connect, Skyward ORM compares every loaded table class with the live schema and refuses to start if they disagree:
187
227
 
188
228
  ```
189
229
  Skyward::ORM::SchemaMismatch: Todo doesn't match the todos table
190
230
 
191
- notes todos has no column notes.
192
- Run `skyward migrate`, or `skyward migration` if you haven't generated one.
231
+ notes todos has no column notes.
232
+ Run `skyward migrate`, or `skyward migration` if you haven't generated one.
193
233
  ```
194
234
 
195
- A table class loaded after connect is checked the first time it's used.
235
+ It looks for each table and column the class declares, and for a typed column, a compatible type and the same nullability. A column without a type only has to be there. Columns the class doesn't declare, indexes and constraints aren't compared, and `skyward status` lists those differences. A table class loaded after connect is checked the first time it's used.
236
+
237
+ `Skyward.connect(url, check: false)` skips the check, for what fixes a mismatch. The migration commands turn it off for their process before they boot your app, so the `Skyward.connect(url)` in your `boot.rb` needs no change, and `Skyward.migrate` runs the check once it has migrated.
196
238
 
197
239
  ---
198
240
 
@@ -215,17 +257,23 @@ Queries are `Enumerable`, so `each`, `map`, `group_by` and friends work, and the
215
257
 
216
258
  `where` takes the hash conditions you already know, plus the Ruby values that naturally mean something in SQL:
217
259
 
218
- | Ruby | SQL |
219
- | ---------------------------------------- | ----------------------------------------------------------- |
220
- | `where(done: false)` | `done = false` |
221
- | `where(due_on: nil)` | `due_on IS NULL` |
222
- | `where(priority: [:high, :normal])` | `priority IN ('high', 'normal')` |
223
- | `where(due_on: ..Date.today)` | `due_on <= '2026-10-18'` |
224
- | `where(due_on: Date.today...)` | `due_on >= '2026-10-18'` |
225
- | `where(created_at: from...to)` | `created_at >= ? AND created_at < ?` |
226
- | `exclude(done: true)` | `NOT (done = true)` |
227
- | `where(done: false).or(priority: :high)` | `done = false OR priority = 'high'` |
228
- | `where("title ILIKE ?", "%milk%")` | `title ILIKE '%milk%'`, with the value bound as a parameter |
260
+ | Ruby | SQL |
261
+ | ---------------------------------------- | ------------------------------------------------------------- |
262
+ | `where(done: false)` | `done = false` |
263
+ | `where(due_on: nil)` | `due_on IS NULL` |
264
+ | `where(priority: [:high, :normal])` | `priority IN ('high', 'normal')` |
265
+ | `where(due_on: ..Date.today)` | `due_on <= '2026-10-18'` |
266
+ | `where(due_on: Date.today...)` | `due_on >= '2026-10-18'` |
267
+ | `where(created_at: from...to)` | `created_at >= ? AND created_at < ?` |
268
+ | `exclude(done: true)` | `NOT (done = true)` |
269
+ | `where(done: false).or(priority: :high)` | `done = false OR priority = 'high'` |
270
+ | `where("title ILIKE ?", "%milk%")` | `(title ILIKE '%milk%')`, with the value bound as a parameter |
271
+
272
+ A range with only one end compares with that end alone, and a range with neither end raises `ArgumentError`. An SQL string goes in parentheses, and each `?` in it binds the next value, numbered on from the query's other values in the connected database's placeholder style. A `?` inside a quoted string, a quoted name or a comment is the SQL's own and is left as it is. When the query runs or shows its SQL, a count of `?` that doesn't match the values raises `ArgumentError`, and so does an `Array` or `Hash` value, which the driver would spread across several placeholders.
273
+
274
+ `exclude` takes what `where` takes and wraps it in `NOT (...)`. In SQL, `NOT` of a comparison with `NULL` is unknown, so it would leave out a row whose column is `NULL`, though that row doesn't match. So on a nullable or untyped column, `exclude` keeps the `NULL` rows: `exclude(due_on: Date.today)` is `(NOT (due_on = '2026-10-18') OR due_on IS NULL)`. A condition that matches `NULL` itself, such as `exclude(due_on: nil)`, is a plain `NOT`, and so is an SQL string, whose columns Skyward ORM can't know.
275
+
276
+ `or` takes what `where` takes and joins it to everything before it: `where(a).where(b).or(c)` is `(a AND b) OR c`, and a later `where(d)` makes it `((a AND b) OR c) AND d`. A query with no conditions has nothing to `or` with, and neither does an `or` given nothing, so each raises `ArgumentError`. An `exclude` given nothing keeps the query's conditions, but it no longer counts as an explicit `Todo.all` (see [Writing](#writing)).
229
277
 
230
278
  Order and paging: `order(:title)`, `order(created_at: :desc)`, `limit(20)` and `offset(40)`.
231
279
 
@@ -257,12 +305,17 @@ A file that names Skyward ORM's types in its signatures starts with `# @rbs use
257
305
  Every query can show its SQL without running it:
258
306
 
259
307
  ```ruby
260
- Todo.where(done: false, priority: [:high, :normal]).order(created_at: :desc).to_sql
261
- # => ["SELECT id, list_id, title, priority, due_on, done, created_at FROM todos
262
- # WHERE done = $1 AND priority IN ($2, $3) ORDER BY created_at DESC",
263
- # [false, "high", "normal"]]
308
+ sql, binds = Todo.where(done: false, priority: [:high, :normal]).order(created_at: :desc).to_sql
309
+
310
+ puts sql
311
+ # SELECT "id", "list_id", "title", "priority", "due_on", "done", "created_at" FROM "todos"
312
+ # WHERE "done" = $1 AND "priority" IN ($2, $3) ORDER BY "created_at" DESC
313
+
314
+ binds # => [false, "high", "normal"]
264
315
  ```
265
316
 
317
+ Every table and column name is quoted, so a column named `order` or `user` works like any other. The placeholders and values are the ones the connected database is sent: on SQLite the placeholders are `?` and `false` is `0`.
318
+
266
319
  ### Related rows
267
320
 
268
321
  Skyward ORM has no associations, so nothing loads behind your back and N+1 queries can't hide. Loading related rows takes two queries and some `Enumerable`:
@@ -303,13 +356,17 @@ Todo.where(done: false).group(:list_id).into(OpenCount, open: "count(*)")
303
356
  # SELECT list_id, count(*) AS open FROM todos WHERE done = false GROUP BY list_id
304
357
  ```
305
358
 
359
+ An expression is raw SQL that goes into the query exactly as written, so it must be trusted: never build one from user input. Pass user input to `where`, which binds it as a parameter.
360
+
361
+ `into` returns a `Skyward::ORM::Projection[TodoTitle]`, a query like any other except that its writes return rows of its class (see [Writing](#writing)). It can come anywhere in a query, and `Todo.into(TodoTitle)` starts one from every row.
362
+
306
363
  `join` is an inner join and `left_join` is a left join. A member without an expression reads from the table the query started from, so `id` above is `todos.id`. A joined table's columns always need an expression.
307
364
 
308
365
  ---
309
366
 
310
367
  ## Raw SQL
311
368
 
312
- Skyward ORM builds SQL. It doesn't hide it. When a query is easier to write than to build, write it, and name the shape you want back:
369
+ When a query is easier to write than to build, write it, and name the shape you want back:
313
370
 
314
371
  ```ruby
315
372
  Overdue = Data.define(:title, :days_late)
@@ -329,23 +386,45 @@ Values are always bound as parameters, never interpolated. If you leave out the
329
386
 
330
387
  ## Writing
331
388
 
332
- Writes return what they wrote, using `RETURNING`, so you never need a second query to see the result:
389
+ A write returns how many rows it changed, unless you ask for rows with `into`. [Drizzle](https://orm.drizzle.team) is the model: a write gives nothing back unless you ask, so it never reads more than you use.
390
+
391
+ ```ruby
392
+ Todo.insert(title: "Buy milk", list_id: 1) # => 1
393
+ Todo.insert_all([{ title: "Eggs", list_id: 1 }, ...]) # => Integer, the rows inserted
394
+ Todo.where(id: 42).update(done: true) # => Integer, the rows updated
395
+ Todo.where(done: true).delete # => Integer, the rows deleted
396
+ ```
397
+
398
+ `into` names the rows to return instead, through `RETURNING` of just its members' columns, or every column for the table class itself. It can come anywhere before the write. `insert` returns its one row, and `update` and `delete` return an `Array`:
333
399
 
334
400
  ```ruby
335
- Todo.insert(title: "Buy milk", list_id: 1) # => Todo
336
- Todo.insert_all([{ title: "Eggs", list_id: 1 }, ...]) # => Array[Todo]
337
- Todo.where(id: 42).update(done: true) # => Array[Todo], the updated rows
338
- Todo.where(done: true).delete # => Array[Todo], the deleted rows
401
+ Id = Data.define(:id)
402
+
403
+ Todo.into(Todo).insert(title: "Buy milk", list_id: 1) # => Todo, every column
404
+ Todo.into(Id).insert(title: "Buy milk", list_id: 1) # => Id, RETURNING "id"
405
+ Todo.where(id: 42).into(Todo).update(done: true) # => Array[Todo], the updated rows
406
+ Todo.where(done: true).into(Id).delete # => Array[Id], the deleted rows' ids
407
+ ```
408
+
409
+ `insert` on a query takes nothing but `into`. Anything else on the query, such as a `where`, an `order` or a join, raises an `ArgumentError` before any SQL runs.
410
+
411
+ Columns with a default (`id`, `done`, `created_at`) and nullable ones (`due_on`) are optional. The rest are required, and leaving one out raises an `ArgumentError` straight away, as does a column the class doesn't have, a value its column's type doesn't take, or an Array or a Range, which is never one value. A column without a type is left to the database, and `insert` with no columns inserts a row of defaults.
412
+
413
+ `update` and `delete` change every row the query matches, so a query with no conditions would change the whole table. That raises an `ArgumentError`, unless the query is an explicit `Todo.all`, which says you mean every row. A `where` or `exclude` narrows it, even one given nothing, so it no longer counts:
414
+
415
+ ```ruby
416
+ Todo.where(**filters).delete # ArgumentError when filters is empty
417
+ Todo.all.update(done: false) # every todo
339
418
  ```
340
419
 
341
- Columns with a default (`id`, `done`, `created_at`) and nullable ones (`due_on`) are optional. The rest are required, and leaving one out raises an `ArgumentError` straight away.
420
+ A query with a join, `group`, `order`, `limit` or `offset`, or `into` a class with SQL expressions, can't be updated or deleted, because PostgreSQL and SQLite don't both support them there, so it raises an `ArgumentError` too, as does `update` with no columns.
342
421
 
343
422
  ### When the database says no
344
423
 
345
- A duplicate email or a missing parent row isn't exceptional. It's an outcome your code should handle. So the plain write methods return either the rows or a `Skyward::ORM::Violation`:
424
+ A duplicate email or a missing parent row is an outcome your code should handle, so the plain write methods return either their count or rows, or a `Skyward::ORM::Violation`:
346
425
 
347
426
  ```ruby
348
- result = User.insert(email:)
427
+ result = User.into(User).insert(email:)
349
428
  case result
350
429
  when User then created result
351
430
  else result.kind == :unique ? conflict("That email is already registered") : unprocessable(result.message)
@@ -356,10 +435,14 @@ Steep 2.1 can't type-check `case`/`in`, so typed code matches on the class with
356
435
 
357
436
  `Skyward::ORM::Violation` has `kind` (`:unique`, `:foreign_key`, `:not_null` or `:check`), `constraint`, `columns` and the database's `message`.
358
437
 
359
- When a violation would mean a bug, use the bang version. It returns the rows or raises `Skyward::ORM::ViolationError`, the way `save` and `save!` work in ActiveRecord:
438
+ Deleting a row that other rows still reference returns a `:foreign_key` violation when the reference's `on_delete` is `:restrict` or unset. Its `constraint` and `columns` describe the referencing table's foreign key, such as `todos_list_id_fkey` and `[:list_id]` when a `Todo` still references the `List`, because that's the constraint that failed.
439
+
440
+ When a violation would mean a bug, use the bang version: `insert!`, `update!` or `delete!`. It returns the same count or rows, or raises `Skyward::ORM::ViolationError`, which carries the violation, the way `save` and `save!` work in ActiveRecord:
360
441
 
361
442
  ```ruby
362
- Todo.insert!(title: "Buy milk", list_id: 1) # => Todo
443
+ Todo.into(Todo).insert!(title: "Buy milk", list_id: 1) # => Todo
444
+ Todo.where(id: 42).update!(done: true) # => Integer
445
+ Todo.where(done: true).into(Id).delete! # => Array[Id]
363
446
  ```
364
447
 
365
448
  ---
@@ -368,7 +451,7 @@ Todo.insert!(title: "Buy milk", list_id: 1) # => Todo
368
451
 
369
452
  ```ruby
370
453
  Skyward.transaction do
371
- list = List.insert!(name: "Groceries")
454
+ list = List.into(List).insert!(name: "Groceries")
372
455
  Todo.insert!(title: "Milk", list_id: list.id)
373
456
  end
374
457
  ```
@@ -377,7 +460,7 @@ Every query inside the block runs in the transaction, and the block's value is r
377
460
 
378
461
  ```ruby
379
462
  result = Skyward.transaction do
380
- user = User.insert(email:)
463
+ user = User.into(User).insert(email:)
381
464
  case user
382
465
  when User then Membership.insert(user_id: user.id, team_id:)
383
466
  else user # a violation: rolls back, then returns it
@@ -391,11 +474,11 @@ A transaction belongs to the fiber that opened it. Ruby copies fiber storage int
391
474
 
392
475
  ## Types
393
476
 
394
- Skyward ORM reads the same RBS as Steep, whether it's written inline or in `sig/`. It reads the `.rbs` files, so inline types count once rbs-inline has written them to `sig/`. Here's what gets checked, and when:
477
+ Skyward ORM reads the same RBS as Steep, whether it's written inline or in `sig/`. It reads the `.rbs` files, and the CLI regenerates `sig/generated` from your inline types before it reads them, so you never run rbs-inline yourself. Here's what gets checked, and when:
395
478
 
396
479
  | When | What's checked |
397
480
  | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
398
- | **As you type (Steep)** | The row type of every query. `Todo.where(...)` is a `Skyward::ORM::Query[Todo]`, `.to_a` is an `Array[Todo]`, `.into(TodoTitle)` is a `Query[TodoTitle]`, and `insert` returns `Todo \| Skyward::ORM::Violation`. No annotations are needed. |
481
+ | **As you type (Steep)** | The row type of every query. `Todo.where(...)` is a `Skyward::ORM::Query[Todo]`, `.to_a` is an `Array[Todo]`, `.into(TodoTitle)` is a `Projection[TodoTitle]`, `insert` returns `Integer \| Skyward::ORM::Violation`, and `.into(Todo).insert` returns `Todo \| Skyward::ORM::Violation`. No annotations are needed. |
399
482
  | **When you generate a migration** | Column types, nullability and enum values all come from your types. |
400
483
  | **At connect** | Every table class against the live schema, which catches migrations you haven't run. |
401
484
  | **When a query is built** | Column names exist, and values match their column's type. `where(dnoe: false)` and `where(done: "yes")` both raise immediately, so your first test run catches them. |
@@ -405,21 +488,21 @@ Types are what Skyward ORM generates migrations from. Leave them off and queries
405
488
 
406
489
  ### How types map
407
490
 
408
- | RBS | PostgreSQL | SQLite |
409
- | ----------------------- | ------------------------------------------------ | ----------------- |
410
- | `Integer` | `bigint` | `INTEGER` |
411
- | `Float` | `double precision` | `REAL` |
412
- | `BigDecimal` | `numeric` | `TEXT` |
413
- | `String` | `text` | `TEXT` |
414
- | `bool` | `boolean` | `INTEGER` (0/1) |
415
- | `Date` | `date` | `TEXT` (ISO 8601) |
416
- | `Time` | `timestamptz` | `TEXT` (ISO 8601) |
417
- | `:low \| :high` | `text` with a check, read back as Symbols | `TEXT` with a check |
418
- | `T?` | a nullable column | a nullable column |
419
- | `Hash[String, untyped]` | `jsonb` | `TEXT` (JSON) |
420
- | `Array[T]` | `T[]` | `TEXT` (JSON) |
421
-
422
- This is the type in a generated migration. When reading an existing column, Skyward ORM also accepts compatible types, such as `integer` or `varchar`. These mappings match Skyward API's, so a `Todo` read from the database and a `Todo` sent as JSON are the same thing.
491
+ | RBS | PostgreSQL | Also compatible on PostgreSQL | SQLite |
492
+ | --------------------------------------- | ----------------------------------------- | ----------------------------- | ------------------- |
493
+ | `Integer` | `bigint` | `integer`, `smallint` | `INTEGER` |
494
+ | `Float` | `double precision` | `real` | `REAL` |
495
+ | `BigDecimal` (still to come) | `numeric` | | `TEXT` |
496
+ | `String` | `text` | `varchar`, `uuid`, `citext` | `TEXT` |
497
+ | `bool` | `boolean` | | `INTEGER` (0/1) |
498
+ | `Date` | `date` | | `TEXT` (ISO 8601) |
499
+ | `Time` | `timestamptz` | `timestamp` | `TEXT` (ISO 8601) |
500
+ | `:low \| :high` | `text` with a check, read back as Symbols | `varchar` | `TEXT` with a check |
501
+ | `T?` | a nullable column | | a nullable column |
502
+ | `Hash[String, untyped]` (still to come) | `jsonb` | | `TEXT` (JSON) |
503
+ | `Array[T]` (still to come) | `T[]` | | `TEXT` (JSON) |
504
+
505
+ The PostgreSQL and SQLite columns are the types a generated migration writes. Edit a column in one to a compatible type and Skyward ORM keeps it: `Skyward.connect` accepts it, and `skyward migration` leaves it as it is. On PostgreSQL, that's a type in the compatible column, with any length or precision, and on SQLite any type with the same affinity, such as `bigint` or `varchar(255)`. A value a compatible type can't hold, such as `"nope"` for a `uuid`, raises the database's error. These mappings match Skyward API's, so a `Todo` read from the database and a `Todo` sent as JSON are the same thing.
423
506
 
424
507
  ---
425
508
 
@@ -429,19 +512,19 @@ Test against a real database. In-memory SQLite or a local PostgreSQL is fast eno
429
512
 
430
513
  ```ruby
431
514
  # test/test_helper.rb
432
- Skyward.connect(ENV.fetch("TEST_DATABASE_URL"))
433
- Skyward.migrate("db/migrate") # runs any migration the test database hasn't had
515
+ Skyward.connect(ENV.fetch("TEST_DATABASE_URL"), check: false)
516
+ Skyward.migrate("db/migrate") # runs any migration the test database hasn't had, then checks the schema
434
517
  ```
435
518
 
436
519
  ```ruby
437
520
  describe Todo do
438
521
  include Skyward::ORM::Transactional # each test runs in a transaction that's rolled back afterwards
439
522
 
440
- let(:list) { List.insert!(name: "Home") }
523
+ let(:list) { List.into(List).insert!(name: "Home") }
441
524
 
442
525
  describe ".overdue" do
443
526
  it "skips todos that are done" do
444
- late = Todo.insert!(title: "Milk", list_id: list.id, due_on: Date.new(2026, 10, 1))
527
+ late = Todo.into(Todo).insert!(title: "Milk", list_id: list.id, due_on: Date.new(2026, 10, 1))
445
528
  Todo.insert!(title: "Eggs", list_id: list.id, due_on: Date.new(2026, 10, 1), done: true)
446
529
 
447
530
  assert_equal [late], Todo.overdue(today: Date.new(2026, 10, 18)).to_a
@@ -452,6 +535,10 @@ end
452
535
 
453
536
  Rows are values, so assertions compare them directly with `==`.
454
537
 
538
+ `Skyward::ORM::Transactional` opens the transaction before setup and rolls it back after teardown, whether the test passed, failed or raised, so the rows `let` and `before` write go with it. A `Skyward.transaction` in the test is a savepoint, so a violation it returns rolls back only its own writes, and the test can still assert on what came before. `Skyward.transaction?` is false in the test itself and true only inside a `Skyward.transaction`, so code that branches on it behaves as it does in production.
539
+
540
+ The test's transaction belongs to the test's fiber. A thread or fiber the test starts that queries raises `FiberError`, as it would inside a `Skyward.transaction` in production, so return its result to the test instead.
541
+
455
542
  ---
456
543
 
457
544
  ## Performance
@@ -474,18 +561,18 @@ Skyward ORM and Skyward API share one `skyward` command. Each adds its own comma
474
561
  | `skyward migration --empty backfill` | writes an empty migration for SQL you write yourself |
475
562
  | `skyward migrate` | runs pending migrations |
476
563
  | `skyward rollback` | runs the `-- down` section of the latest migration |
477
- | `skyward status` | lists migrations, and any differences between your classes and the database |
564
+ | `skyward status` | lists migrations, and any differences between your classes and the database, and exits 1 if anything needs doing |
478
565
  | `skyward scaffold todos` | prints a table class for an existing table, for adopting a database Skyward ORM didn't create |
479
566
 
480
- The CLI runs in your app's directory and requires its `boot.rb`, which loads your table classes and calls `Skyward.connect`.
567
+ The CLI runs in your app's directory and requires its `boot.rb`, which loads your table classes and calls `Skyward.connect`. First it regenerates `sig/generated` from your inline types, when rbs-inline is in your bundle, so it compares the types your Ruby has now. The migration commands turn the schema check off before they require it, because they're what fixes a mismatch. `skyward migration --empty` compares nothing, so it skips `boot.rb` and works before your app can connect.
481
568
 
482
569
  ---
483
570
 
484
- ## Coming from…
571
+ ## Coming from other libraries
485
572
 
486
- - **ActiveRecord.** `Todo.where` works the way you expect, and `insert`/`insert!` work like `save`/`save!`. But a row is data rather than an object with a lifecycle: it has no callbacks, validations or associations. The columns are written in the class, so you can see them, and migrations are written for you from them.
487
- - **Sequel.** It's the same idea of queries as values, but the rows are instances of your own typed classes rather than hashes or models.
488
- - **Django or Prisma.** It's the same declare-then-generate approach to migrations, in plain Ruby with RBS types.
573
+ - **ActiveRecord.** `Todo.where` works the way you expect, and `insert`/`insert!` work like `save`/`save!`. A row is data, with no lifecycle: it has no callbacks, validations or associations. The columns are written in the class, where you can see them, and the migrations are written from them.
574
+ - **Sequel.** Queries are values here too. The rows are instances of your own typed classes, not hashes or models.
575
+ - **Django or Prisma.** The same declare-then-generate approach to migrations, in plain Ruby with RBS types.
489
576
  - **Raw SQL.** Use it whenever you like (`Skyward.query`), and keep typed results and bound parameters.
490
577
 
491
578
  ---
@@ -495,12 +582,32 @@ The CLI runs in your app's directory and requires its `boot.rb`, which loads you
495
582
  1. **A class is a table, and its rows are values.** You query the class, and you get back frozen instances of it that you can use anywhere.
496
583
  2. **The class is the schema.** Columns, types and constraints are declared once, in Ruby, where Steep and Skyward ORM can both read them. Migrations follow from them.
497
584
  3. **A query is a value.** It's immutable, composable and printable, and nothing runs until you ask for rows.
498
- 4. **SQL is the feature, not the problem.** Skyward ORM builds the SQL you'd write yourself, writes your migrations in SQL you can read, and lets you write it yourself when that's clearer.
499
- 5. **Outcomes are values.** The database saying no is a result you handle, not an exception you rescue.
585
+ 4. **SQL stays in view.** Skyward ORM builds the SQL you'd write yourself, writes migrations as SQL you can read, and lets you write your own when that's clearer.
586
+ 5. **Outcomes are values.** When the database says no, you get a `Skyward::ORM::Violation` to match on with `case`/`when`.
500
587
  6. **No hidden work.** Skyward ORM has no lazy loading and no callbacks. Every query is one you can see.
501
588
 
502
589
  ---
503
590
 
504
591
  ## Status
505
592
 
506
- This README is the spec. Skyward 0.1 is a skeleton: the gem installs and loads, and none of the features above are built yet. Skyward ORM is built after Skyward API, and this section lists each part as it lands.
593
+ This README is the spec, and this section lists each part of it that's built, as it lands. Anything it describes that isn't listed here isn't built yet.
594
+
595
+ - **Tables.** A table class subclasses `Skyward::ORM::Record`, and each `attr_reader` adds a column, in order. Skyward ORM registers its signatures with Skyward Core, so an app's signatures can subclass `Skyward::ORM::Record` too. `table`, `primary_key` (`:id` by default), `references` (with an optional `on_delete:` of `:cascade`, `:restrict`, `:set_null`, `:set_default` or `:no_action`), `default`, `unique`, `check` and `index` build one frozen schema for the class, and `Skyward.sql("...")` wraps an SQL expression for `default` and `check`. A malformed declaration raises `ArgumentError` in the class body: a column declared twice, a table or column name that isn't a Symbol, `unique` or `index` with no columns, `references` to anything but a table class or with another `on_delete:`, `Skyward.sql` given anything but a String, and a `check` given a plain String, both SQL and `length:`, neither, or a `length:` that isn't a Range of Integers, has no bound or is empty. A declaration can come before the `attr_reader` it names, so the columns declarations name, the default primary key included, are checked by a validation function that connecting and generating a migration call, which raises `Skyward::Core::BootError` naming the class and each column it doesn't have. A class with no `table` raises `Skyward::Core::BootError` when its table name is asked for, saying to add `table :name`.
596
+ - **Rows.** `Todo.new(**columns)` builds a frozen row, and raises `ArgumentError` naming the columns left out and the ones the class doesn't have. A row has `to_h`, `with`, `deconstruct_keys`, `==`, `eql?`, `hash` and `inspect` (`#<Todo id=1, title="Buy milk", done=false>`), and two rows are `==`, or `eql?`, when they're of the same class and each of their columns is. A table class's `members` are its columns, as a `Data` class's are its members. Each `attr_reader` compiles the class's row methods for its columns so far, so building and comparing a row reads and writes its columns directly, and redefining them never makes Ruby warn.
597
+ - **Column types.** Each column's type is read from the class's RBS through Skyward Core's reader, once per class for the signatures it loaded: `Integer`, `Float`, `String`, `bool`, `Date`, `Time` and a union of symbols, keeping its symbols, with `T?` or `T | nil` nullable and aliases expanded. A column with no type or typed `untyped`, and every column of a class with no signature, is untyped, so its values will pass through as the driver returns them. A column typed as a record, a class, an `Array` or a `Hash` raises `Skyward::Core::BootError` saying it isn't a column type yet, any other type, such as a literal or a union of other types, saying it isn't a column type, and a type Skyward Core can't read with Skyward Core's explanation, each naming the column (`Todo#tags`). A row class's members are read the same way, whether it's a table class or not.
598
+ - **Connecting.** `Skyward.connect(url, signatures: "sig", pool: 5, check:)` loads the signatures under `signatures`, `sig/` in the current directory by default, connects through the adapter the URL's scheme picks, reads the database's schema, and keeps the database for every query, returning it. It pools up to `pool:` connections, opening each only when it's needed. A query outside a transaction checks one out for the current fiber and returns it when done, and when every one is in use it waits for one to come back, blocking only its own fiber, and after 5 seconds raises `Skyward::ORM::PoolTimeout`, saying how long it waited for how many and to pass a larger `pool:`. A connection that comes back with a transaction still open, or on PostgreSQL in any state but idle, is rolled back and reused. One that still isn't idle, or whose rollback fails, is closed, and the pool opens another in its place when one is next needed, keeping the place for the next checkout if that open fails. Nothing a failed rollback or close raises reaches the code that returned the connection. A scheme with no adapter raises `Skyward::Core::BootError` naming the schemes Skyward ORM connects to, without showing the URL. Everything that differs between databases sits behind an adapter: opening a connection, how many it can pool, placeholders, the `LIMIT` an `OFFSET` needs before it, the SQL type for each column type and which declared types are compatible with it, the clause that numbers an integer primary key, whether `ALTER TABLE` can change a column or constraint in place, how a default's SQL expression is written, encoding and decoding values, reading the schema (each table's columns with their declared type, nullability and default as a migration writes it, its indexes with their `CREATE INDEX`, and its constraints with their names, columns and definitions as table constraints), turning a driver error into a `Skyward::ORM::Violation`, and beginning and ending a migration's transaction with its lock and finding the rows a migration left referring to missing ones. A row decoder is built once for each table class, row class and set of members given expressions, and cached: it reads each member by the row class's own RBS type, else by its table's column of that name, with `nil` as `nil` and every string frozen, and passes through a member given an expression, or one its table has no column for, that the row class doesn't type.
599
+ - **Checking the schema.** `Skyward.connect` checks every loaded table class, each subclass of `Skyward::ORM::Record` at any depth that declares a `table`, in order of name. It validates each class's declarations, then compares its columns with the schema it read: a missing table, a missing column, a typed column whose declared type isn't compatible with its column type, and one whose nullability differs from its column's, raise `Skyward::ORM::SchemaMismatch`, a `Skyward::Core::BootError`. Its message has a block for each class that doesn't match, naming the class and its table, then a line for each problem, aligned on the column's name, and the fix below it. An untyped column is only checked for presence, and the database's other columns, its indexes and its constraints are ignored. A table class loaded after connect is checked before it's first queried or written, by `count`, `exists?` or when its first row decoder is built, which every write builds before it runs: once for each class that matches, under a lock so threads check it once, and again each time for one that doesn't. Raw SQL names no table class, so `Skyward.query` isn't checked. `check: false` skips both. Without `check:`, it checks unless the process's session has the check off: `Skyward::ORM::Connection::SESSION.without_check { ... }` turns it off for its block, and `skyward migration`, `skyward migrate`, `skyward rollback` and `skyward status` require `boot.rb` inside it, so they can write, run, undo and report the migration a mismatch needs. `Skyward.migrate` checks every loaded table class once it has migrated, and `skyward migrate` every one `skyward migration` finds, against the schema read again after migrating.
600
+ - **Transactions.** `Skyward.transaction { ... }` checks a connection out and holds it for the whole block. It runs `BEGIN`, then commits and returns the block's value, or rolls back if the block raises (raising it again) or returns a `Skyward::ORM::Violation` (returning it). A block left any other way, such as by `throw`, rolls back, and so does a commit that fails, and a `BEGIN` or savepoint that an exception interrupts once it has reached the database, so the connection always goes back to the pool with no transaction open. When rolling back an interrupted `BEGIN` or savepoint fails, as it does when the start never reached the database, the exception that interrupted it is raised rather than the rollback's failure. On PostgreSQL, a savepoint's failed rollback leaves the enclosing transaction aborted until it rolls back too, so a block that rescues that exception and carries on gets PostgreSQL's "current transaction is aborted". A nested `Skyward.transaction` is a savepoint on the same connection, named by its depth, which rolls back only its own writes. The transaction belongs to the fiber that opened it: a child fiber or thread that inherits it through fiber storage and runs a query raises `FiberError`, "this transaction belongs to another fiber; start your own, or return the result to the block", and one that calls `Skyward.transaction` starts its own, on a connection of its own. `Skyward.transaction?` is true inside the block on the fiber that opened it, and false anywhere else. `Skyward.using` is still to come.
601
+ - **Testing.** A Minitest test class or `describe` block that includes `Skyward::ORM::Transactional` runs each test in a transaction. Its `before_setup` checks a connection out, holds it for the test's fiber and runs `BEGIN`, and its `after_teardown` rolls back and returns the connection to the pool, whether the test passed, failed or raised, and even when another `after_teardown` raises, so rows from `let` and `before` are rolled back too and the next test starts from a clean database. A `Skyward.transaction` in the test is a savepoint on that connection, `Skyward.transaction?` is true only inside one, and a thread or fiber the test starts that queries raises `FiberError`, as it would inside a `Skyward.transaction` in production. It uses Minitest's hooks without requiring Minitest, which stays out of the gemspec.
602
+ - **SQLite.** `sqlite://path` and `sqlite://:memory:` connect with the `sqlite3` gem, which is in the app's Gemfile rather than Skyward ORM's gemspec: the adapter requires it on connect, and without it raises `Skyward::Core::BootError` saying to add `gem "sqlite3"`. It needs SQLite 3.35 or later, for `RETURNING`, and turns foreign keys on. Each connection to `:memory:` opens its own empty database, so it pools one connection whatever `pool:` says, and a connection to a file waits up to 5 seconds on another's lock rather than failing at once, letting other threads and fibers run while it waits. Its types, and the types compatible with them, are as [How types map](#how-types-map) says. A `Time` is stored as fixed-width UTC text to the microsecond, so text order is time order and it reads back `==` to the one written once truncated to microseconds. SQLite takes an `OFFSET` only after a `LIMIT`, so an offset with no limit follows `LIMIT -1`. Constraint names, and their definitions, are read from each table's `CREATE TABLE`: a column's own constraint as the table constraint it's the same as, such as `FOREIGN KEY (list_id) REFERENCES lists`. SQLite reads a default back without the parentheses an expression was written in, so the adapter puts them back on anything but a literal.
603
+ - **PostgreSQL.** `postgres://` and `postgresql://` URLs connect with the `pg` gem, which is in the app's Gemfile rather than Skyward ORM's gemspec: the adapter requires it on connect, and without it raises `Skyward::Core::BootError` saying to add `gem "pg"`. Its placeholders are `$1`, `$2` and so on, and it pools as many connections as `pool:` says. Each session runs with `TimeZone` set to UTC and `DateStyle` to ISO, whatever the server's defaults, and with `client_min_messages` at `warning`, since libpq prints every notice the server sends. Its types, and the types compatible with them, are the PostgreSQL columns of [How types map](#how-types-map). A `Time` is written in UTC to the microsecond, as PostgreSQL writes one back, and reads back `==` to the one written once truncated to microseconds, from a `timestamp` column as well as a `timestamptz`, a `date` reads back as a `Date`, a `boolean` as `true` or `false`, and a symbol union's column as Symbols. The driver returns every value as text, so an untyped column's value, and each value in a hash `Skyward.query` returns, is a String. The schema is read from `pg_catalog`: the tables an unqualified name finds, each column's type, nullability and default, as a migration writes it, without the cast PostgreSQL reads a literal back with (`'normal'` for `'normal'::text`, `-1` for `'-1'::integer`), each index but those its constraints make, with its `CREATE INDEX` as PostgreSQL writes it, and each primary key, unique, foreign key and check constraint by name, with its columns and its definition as PostgreSQL writes it. A migration alters its tables in place, and numbers an integer primary key `GENERATED ALWAYS AS IDENTITY`, so an insert that gives that key a value is refused, as SQLite's `INTEGER PRIMARY KEY` isn't.
604
+ - **Violations.** `Skyward::ORM::Violation` has `kind` (`:unique`, `:foreign_key`, `:not_null` or `:check`), `constraint`, `columns` and the database's `message`. On SQLite the extended result code gives the kind, and the schema read at connect fills in the rest: a unique violation's constraint or unique index from the columns SQLite names, a check's columns from its name, and a foreign key's name and columns from the one foreign key the table written has or that refers to it. Raw SQL doesn't say which table it writes, so its check is looked for in every table, and its foreign key is the one any table has. SQLite doesn't say which foreign key failed, so when there's more than one the violation has neither. A not-null violation names its column and no constraint, and a check with no name has its expression as its constraint and no columns. On PostgreSQL the SQLSTATE gives the kind (`23505` unique, `23503` foreign key, `23502` not null, `23514` check), the constraint is the one the error names, its columns are that constraint's or unique index's in the schema read at connect, or a not-null violation's column, and the message is the server's.
605
+ - **Raw SQL.** `Skyward.query(RowClass, sql, *values)` runs the SQL on the current fiber's connection, inside its transaction if there is one, and returns an `Array` of the row class, which Steep reads as `Array[RowClass]`, and `Skyward.query(sql, *values)` returns an `Array` of symbol-keyed hashes. Each `?` outside a string, a quoted name or a comment becomes the adapter's placeholder, bound to its value as the adapter stores it, and a count of `?` that doesn't match the values, or a value that's an Array or a Hash, raises `ArgumentError`. A row class's members are its `members`, as a `Data` class, a `Struct` or a table class has, or else its keyword parameters. They're matched to the result's columns by name, so a result column with no member, or a member with no result column, raises `ArgumentError` naming it, even when no rows come back. Each member is read by its RBS type, so a SQLite date comes back a `Date`, with `nil` as `nil` and an untyped member passed through frozen, while a hash holds each value as the driver returns it. A constraint the SQL breaks raises `Skyward::ORM::ViolationError`, which carries the `Skyward::ORM::Violation` and its message, and any other error raises as it is.
606
+ - **Keeping types current.** `skyward migration`, but for `--empty`, `skyward migrate`, `skyward rollback` and `skyward status` regenerate `sig/generated` before they require `boot.rb`, with `Skyward::Core::Signatures::Inline.generate` and the rbs-inline in the bundle `skyward` runs in, so they read the types the Ruby has now. Without rbs-inline in the bundle, they use `sig/generated` as it is, and say nothing about it. When rbs-inline fails, they exit 1 with its output, without requiring `boot.rb`. With no `boot.rb`, they regenerate nothing.
607
+ - **Generating migrations.** `skyward migration NAME` requires `boot.rb` from the current directory with the schema check off, eager-loads every Zeitwerk loader, and finds every class below `Skyward::ORM::Record`, however deep, that declares a `table`. It checks each class's declarations name its columns, refuses two classes that declare one table, and compares each with the schema read at connect. A table the database doesn't have is created, after the new tables it references, and then each table that differs from its class is changed to match it. A table with no class is left alone. It writes them to `db/migrate/<UTC timestamp>_NAME.sql`, with a `-- down` section that undoes each change in reverse order, and prints what it found, as [Migrations](#migrations) shows. Each column has the adapter's type, `NOT NULL` unless it's nullable, its default (a `Skyward.sql` expression in parentheses on SQLite), a one-column `unique`, its checks, its symbol union's check and its reference, and multi-column uniques and indexes follow. An integer primary key is the adapter's identity column, SQLite's `INTEGER PRIMARY KEY`. Every constraint and index is named after its table, columns and kind: `todos_pkey`, `todos_list_id_fkey`, `todos_email_key`, `todos_title_check` (`todos_title_check1` for a column's second), and `todos_list_id_done_index`. A column with no type gets `-- TODO: todos.notes needs a type` in place of its definition, and an added required column with no default gets `-- TODO: todos.notes needs a DEFAULT for the rows todos already has`. A name that isn't letters, digits and `_`, or more than one, shows the usage, and a name a migration already has, or a migration in `db/migrate` whose version isn't in `schema_migrations`, stops it, so running it twice can't write the same change twice. When every table matches its class it says so and writes nothing. Each refusal, and a `Skyward::Core::BootError` from booting or from a class, exits 1 with only its message. A changed table gets, in this order: its indexes and constraints the class doesn't declare dropped, then its columns the class doesn't have, then its renames, its new columns, each column whose type isn't compatible, whose default differs (a `DEFAULT NULL` is no default, as PostgreSQL keeps it) or whose `NULL` does, and then the constraints and indexes the class declares that it doesn't have. A column that went is asked about each new column of a compatible type, in order, "Did you rename todos.notes to todos.details? [y/N]", until one is a yes (`y` or `yes`, in any case), and a column it's renamed to isn't asked about again. Without a terminal it exits 1, writing nothing, with "skyward: did you rename todos.notes to todos.details? There's no terminal to ask, so nothing was written. Run `skyward migration` in a terminal to answer.", naming every rename it would have asked about. An untyped column's type and `NULL` aren't compared. A constraint is matched by its name, or, with no name, as SQLite can have, by its kind and columns, and a unique or reference also by its columns, the table it references and what it does `ON DELETE`. A check is matched by its name alone, since PostgreSQL rewrites its expression, so a check whose rule changes keeps its name and isn't noticed: write that migration with `--empty`. An index is matched by its columns, so one under another name is kept, and a unique index, which a class can't declare, is dropped. A new column's own constraints are part of its `ADD COLUMN`. On PostgreSQL, each change is an `ALTER TABLE`: `DROP INDEX` and `CREATE INDEX`, `ADD`/`DROP CONSTRAINT` by name, `DROP`/`RENAME`/`ADD COLUMN`, and `ALTER COLUMN` with `TYPE ... USING col::type`, `SET`/`DROP DEFAULT` and `SET`/`DROP NOT NULL`, each undone by its opposite in reverse order. SQLite does in place only what its `ALTER TABLE` can: add a column that isn't a key and whose default isn't an expression, drop or rename one, and drop or create an index. Anything else rebuilds the table, as [Migrations](#migrations) says, keeping the type an untyped column has, and the down section rebuilds it as it was read, with its constraints as table constraints and its indexes' own `CREATE INDEX`. A dropped column comes back in the down section with `-- todos.notes comes back empty: dropping it lost its data`, and a `DEFAULT` TODO when it's required with none, and a column made `NOT NULL` gets `-- TODO: backfill the NULLs in todos.due_on before it becomes NOT NULL`. PostgreSQL's migrations are written with its adapter's types and DDL, and run in the tests on a real PostgreSQL.
608
+ - **Empty migrations.** `skyward migration --empty NAME`, with `--empty` before or after the name, writes `db/migrate/<UTC timestamp>_NAME.sql` holding an empty up section and a `-- down` line, for SQL you write yourself, and prints its path. Its file name sorts among generated ones, so it'll run in order with them. It takes a name by the same rules, refuses a name a migration already has, and shows the usage given any other flag. It compares nothing, so it doesn't require `boot.rb` and works before the app can connect, and a migration that hasn't run doesn't stop it.
609
+ - **Running migrations.** `Skyward.migrate(directory)` runs each pending `.sql` file in the directory on the database `Skyward.connect` kept, in filename order, and returns the versions it ran. Only the part before a `-- down` line runs. `schema_migrations`, created if it's missing, records each version with a SHA-256 checksum of its up section, line endings normalised, and when it ran. Each migration runs on one connection in its own transaction with its version's row, which first takes a lock one migrator holds at a time and then checks again that the version hasn't run, so two deploys migrating at once run each file once, and a crashed one can't leave the lock behind. On SQLite it turns foreign keys off and checks them before committing, as [Migrations](#migrations) describes, and a migration that leaves a row referring to a missing one rolls back, naming each. SQLite's lock is `BEGIN IMMEDIATE`, and PostgreSQL's is `pg_advisory_xact_lock`, which a second migrator waits on until the first commits, and then sees what it ran. On PostgreSQL foreign keys are checked as each statement writes. A migration that fails rolls back, nothing after it runs, and `Skyward::ORM::MigrationError` names the file with the database's message. So does a migration that can't take the lock, which on SQLite means waiting more than 5 seconds, and on PostgreSQL only a `lock_timeout` the server or session sets, and its connection is left with no transaction open. Before running anything, it raises `Skyward::ORM::MigrationError` naming each migration whose up section changed after it ran. Changing a `-- down` section is fine, and a migration that ran but whose file is gone doesn't stop the rest, so old migrations can be squashed. Once it has migrated, even with nothing pending, it reads the schema again on the same connection and checks the table classes against it, raising `Skyward::ORM::SchemaMismatch` for one that doesn't match. `skyward migrate` requires `boot.rb` from the current directory with the schema check off, as `skyward migration` does, runs `db/migrate`, prints `Migrated <version>` for each or `No pending migrations.`, and then checks. A failed or refused migration, a mismatch, and a `Skyward::Core::BootError` from booting, exits 1 with only its message.
610
+ - **Rolling back.** `skyward rollback` requires `boot.rb` with the schema check off, as `skyward migrate` does, and undoes the latest migration, the greatest version in `schema_migrations`, one migration a run. It takes the same lock in its own transaction, checks again that the version is still the latest, runs the migration's `-- down` section, with foreign keys off and checked before it commits on SQLite, and checked as each statement writes on PostgreSQL, and deletes its row, then prints `Rolled back <version>`. It rolls back nothing, and exits 1 with only its reason, when no migration has run, when the latest one's file is gone, when its `-- down` section is blank, when it can't take the lock, or when another migrator ran or rolled back a migration while it waited for the lock. A `-- down` section that fails is undone, and it names the file with the database's message. It reads the schema again afterwards, as migrating does.
611
+ - **Migration status.** `skyward status` requires `boot.rb` with the schema check off, and lists each migration in `db/migrate` in order, as ran, pending, or edited after it ran (its up section's checksum differs), with each version that ran but whose file is gone among them. Then it shows how each table class `skyward migration` finds differs from the database, as `skyward migration` summarises it, except that a column that may have been renamed shows as one dropped and one added, since it doesn't ask, and then each table no class declares, other than `schema_migrations`. When there's nothing to report, it says so. It only reads, so it doesn't create `schema_migrations`. It exits 1 when a migration is pending, edited or gone, a class differs from its table, or a table has no class, so CI can gate on it, and with only its message for a `Skyward::Core::BootError`.
612
+ - **Reading.** `Todo.all` is a query of every row on the connected database, and `Todo.join`, `Todo.left_join`, `Todo.where`, `Todo.exclude`, `Todo.order` and `Todo.find_by` start from it, so Steep types each as a `Skyward::ORM::Query[Todo]` with no annotations. `Todo.into` starts a `Skyward::ORM::Projection` of every row that, unlike `Todo.all`, can't update or delete every row. A query is frozen, and `join`, `left_join`, `where`, `exclude`, `or`, `order`, `group`, `limit` and `offset` each return a new one. `where(column: value)` is `=`, `nil` is `IS NULL` and an array is `IN`: an empty array matches nothing without emitting `IN ()`, and an array holding `nil` matches `IS NULL` too. A range compares with its ends, `>=` its beginning and `<=` its end, or `<` an excluded end, leaving out an end it doesn't have, and a range with neither end raises `ArgumentError`. `where("sql", *values)` adds the SQL in parentheses, each `?` in it becoming the adapter's placeholder, numbered on from the query's other values, while a `?` inside a quoted string, a quoted name or a comment is left as it is. A count of `?` that doesn't match the values, or an `Array` or `Hash` value, which the driver would spread across several placeholders, raises `ArgumentError` when the query runs or shows its SQL. `exclude` takes what `where` takes and adds `NOT (...)`, keeping the `NULL` rows of a nullable or untyped column, which SQL's `NOT` would leave out, with `OR column IS NULL`, unless the condition matches `NULL` itself: an SQL string's columns can't be known, so it's a plain `NOT`. `or` takes what `where` takes too, and joins it to everything before it, so `where(a).where(b).or(c).where(d)` is `((a AND b) OR c) AND d`, and on a query with no conditions, or given nothing, it raises `ArgumentError`, while an `exclude` given nothing keeps the query's conditions but no longer counts as an explicit `Todo.all`. Repeated `where`s and `exclude`s are joined with `AND`, and `order(:title, created_at: :desc)` and `group` append to what's there. A column the table doesn't have raises `ArgumentError` as the query is built, with a "did you mean" suggestion when one is close, and so does an order direction other than `:asc` or `:desc`. Each value given to `where`, `exclude`, `or` or `find_by` as a hash condition is checked against its column's type from the cached column types as the query is built, and one the type doesn't take raises `ArgumentError` naming the class, column, declared type and value: `Todo.done is bool, not "yes" (String)`. `Integer` takes Integers, `Float` Integers and Floats but `NaN`, which SQLite stores as `NULL`, `String` Strings, `bool` `true` and `false`, `Date` Dates but not DateTimes, `Time` Times, and a union of symbols only its own Symbols, while `nil` passes only for a nullable column. Each element of an array is checked, and so is each end of a range, with an open end left unchecked. An untyped column takes any value but a Hash, or an Array inside the array or at an end of a range, since the driver would spread either across several placeholders. `insert` and `update` check their values against the same types, each as one value, so an Array or a Range is refused rather than unpacked. `limit(n)` and `offset(n)` take a non-negative Integer, raising `ArgumentError` for anything else as the query is built, and a later call replaces the earlier value. Both are bound as parameters, so every page of a query shares one SQL string. `first` runs with `LIMIT 1` in place of the query's limit, keeping its offset, ordered by the primary key when nothing else orders it, so both databases return the same row, and returns a row or `nil`. `find_by(**conditions)` is `where(...).first`. `count` runs `COUNT(*)` without the query's order, and counts the groups of a grouped query, and the rows a limited or offset query's page holds, through a subquery. `exists?` runs `SELECT 1` with `LIMIT 1`, keeping the offset but not the order, and returns `true` or `false`, `false` for a limit of 0. `each` and every `Enumerable` method run the query once per call, and `each` without a block returns an `Enumerator`. `to_sql` returns the SQL and the encoded values it binds, in the connected adapter's placeholder style, without running anything. Every table and column name is quoted, with an embedded double quote doubled, so a column named `order`, `group` or `user` can be queried. Rows are decoded with the cached decoder. `into(RowClass, **expressions)` returns a `Skyward::ORM::Projection[RowClass]`, a query whose writes return rows, with every other clause kept, every clause after it keeps it one, and calling it again replaces the projection. The row class's members are found as `Skyward.query` finds them. A member with no expression selects the table's column of that name, and one with an expression selects it as `expr AS "member"`, written into the SQL as given. A member that's neither a column nor given an expression, and an expression for a name that isn't a member, raise `ArgumentError` as the query is built. `where`, `exclude`, `or`, `order` and `group` still name the table's columns, and the values of `where`, `exclude` and `or` are still checked against those columns' types. `join(List, list_id: :id)` adds `JOIN "lists" ON "todos"."list_id" = "lists"."id"`, and `left_join` takes the same and adds `LEFT JOIN`: each key names a column of the starting table and its value a column of the joined one, and more than one pair is joined with `AND`. A class that isn't a table class, a table already in the query, since aliases aren't supported, no pairs, and a column either table doesn't have, with a "did you mean" suggestion, raise `ArgumentError` as the query is built. Once a query has a join, every column it names itself is qualified with its table: each member it selects without an expression, and the columns of `where`, `exclude`, `or`, `order`, `group` and `first`'s primary key, which all mean the starting table's. A joined table's columns are read through an expression, such as `list_name: "lists.name"`, and matched with an SQL string, such as `where("lists.archived = ?", false)`. Without `into`, a joined query returns rows of the starting table, one for each row it matches, and a member filled from a `left_join` is `nil` when no row matches. `count`, `exists?` and running the query check each table class it joins, as they check the one it starts from. `merge` and caching SQL by shape are still to come.
613
+ - **Writing.** `Todo.insert(**values)` inserts a row and returns how many rows it inserted, 1, or a `Skyward::ORM::Violation`, so Steep types it as `Integer | Skyward::ORM::Violation` with no annotations, and given no values it inserts `DEFAULT VALUES`. A column the class doesn't have, or a required one left out (one that isn't nullable, has no `default` and isn't the primary key), raises `ArgumentError` naming it before any SQL runs, as does a value its column's type doesn't take. An Array or a Range is never one value, for any column, so a write refuses it rather than unpacking it as `where` does. A column with no type, like one the class doesn't declare, is left to the database. `update(**values)` on a query sets the values on the rows it matches and returns how many it changed, or a violation, checking each value's type the same way, and raises `ArgumentError` given no values. `delete` on a query deletes the rows it matches and returns how many it deleted, or a violation, usually a foreign key whose `on_delete` is `:restrict` or unset, whose `constraint` and `columns` are the referencing table's foreign key, since that's the one that failed. Each write is one statement with no `RETURNING`, and its count is the one the driver gives for it, which leaves out rows a cascade changed. On a `Skyward::ORM::Projection`, from `into(RowClass)` anywhere before the write, each write returns rows of the row class instead, through `RETURNING` of just its members' columns, or every column for the table class itself: `insert(**values)` its one row, and `update` and `delete` an `Array`, so Steep types them as `RowClass | Skyward::ORM::Violation` and `Array[RowClass] | Skyward::ORM::Violation`. `insert` on a projection raises `ArgumentError` before any SQL runs, naming each clause, unless the query has nothing but `into`: conditions, even from a `where` or `exclude` given nothing, `into` expressions, a `join` or `left_join`, `order`, `group`, `limit` or `offset`. Each write checks its table class against the schema, as a query does, and runs inside the fiber's transaction if there is one. `update` and `delete` raise `ArgumentError` on a query `into` a class with expressions, or with a `join` or `left_join`, `order`, `group`, `limit` or `offset`, which PostgreSQL and SQLite don't both support there, and on one with no conditions from `where`, `exclude` or `or`, which would change every row, unless it's an explicit `Todo.all` that no `where` or `exclude` has narrowed, even one given nothing, so `Todo.all.into(Id).delete` deletes every row while `Todo.into(Id).delete` raises. `insert!`, `update!` and `delete!` return the same count or rows, or raise `Skyward::ORM::ViolationError`, which carries the violation and its message. A violation the plain methods return rolls back the `Skyward.transaction` block it's returned from. `insert_all` is still to come.
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ # PG::Connection runs SQL with exec_params, which returns a PG::Result, so this
4
+ # gives it the execute every adapter's connection has.
5
+ class Skyward::ORM::Adapters::PostgreSQL::Connection
6
+ # @rbs @connection: PG::Connection
7
+ # @rbs @changes: Integer
8
+
9
+ # @rbs connection: PG::Connection
10
+ # @rbs return: void
11
+ def initialize(connection)
12
+ @connection = connection
13
+ @changes = 0
14
+ end
15
+
16
+ # The block form clears each result as soon as its rows are read, so the
17
+ # rows it changed are kept for changes, as SQLite keeps them for its own.
18
+ # @rbs sql: String
19
+ # @rbs binds: Array[untyped]
20
+ # @rbs return: Array[Array[String?]]
21
+ def execute(sql, binds = [])
22
+ @connection.exec_params(sql, binds) do |result|
23
+ @changes = result.cmd_tuples
24
+ result.values
25
+ end
26
+ end
27
+
28
+ # @dynamic changes
29
+ attr_reader :changes #: Integer
30
+
31
+ # @rbs sql: String
32
+ # @rbs *binds: untyped
33
+ # @rbs return: Array[Array[String?]]
34
+ def execute2(sql, *binds) = @connection.exec_params(sql, binds) { |result| [result.fields, *result.values] }
35
+
36
+ # exec, unlike exec_params, runs every statement in the SQL.
37
+ # @rbs sql: String
38
+ # @rbs return: void
39
+ def execute_batch(sql)
40
+ @connection.exec(sql).clear
41
+ end
42
+
43
+ # Anything but idle counts, so a connection left mid-command or broken isn't
44
+ # reused either.
45
+ # @rbs return: bool
46
+ def transaction_active? = @connection.transaction_status != PG::PQTRANS_IDLE
47
+
48
+ # @rbs return: void
49
+ def close
50
+ @connection.close
51
+ end
52
+ end