skyward-orm 0.2.0 → 0.4.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 (206) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +351 -75
  3. data/lib/skyward/orm/adapters/postgresql/connection.rb +52 -0
  4. data/lib/skyward/orm/adapters/postgresql.rb +385 -0
  5. data/lib/skyward/orm/adapters/sqlite/constraints.rb +190 -0
  6. data/lib/skyward/orm/adapters/sqlite.rb +426 -0
  7. data/lib/skyward/orm/adapters.rb +48 -0
  8. data/lib/skyward/orm/catalog/column.rb +13 -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/scaffold/source.rb +304 -0
  18. data/lib/skyward/orm/cli/scaffold.rb +70 -0
  19. data/lib/skyward/orm/cli/status.rb +38 -0
  20. data/lib/skyward/orm/cli.rb +4 -0
  21. data/lib/skyward/orm/commands.rb +76 -0
  22. data/lib/skyward/orm/connection/instrumented.rb +69 -0
  23. data/lib/skyward/orm/connection/pool.rb +102 -0
  24. data/lib/skyward/orm/connection/session.rb +107 -0
  25. data/lib/skyward/orm/connection.rb +7 -0
  26. data/lib/skyward/orm/database/schema_check.rb +79 -0
  27. data/lib/skyward/orm/database.rb +357 -0
  28. data/lib/skyward/orm/execution.rb +9 -0
  29. data/lib/skyward/orm/migration_error.rb +4 -0
  30. data/lib/skyward/orm/migrations/add_column.rb +7 -0
  31. data/lib/skyward/orm/migrations/add_constraint.rb +7 -0
  32. data/lib/skyward/orm/migrations/add_index.rb +7 -0
  33. data/lib/skyward/orm/migrations/alter_table.rb +16 -0
  34. data/lib/skyward/orm/migrations/change_default.rb +9 -0
  35. data/lib/skyward/orm/migrations/change_nullable.rb +8 -0
  36. data/lib/skyward/orm/migrations/change_type.rb +9 -0
  37. data/lib/skyward/orm/migrations/create_table.rb +8 -0
  38. data/lib/skyward/orm/migrations/definitions.rb +179 -0
  39. data/lib/skyward/orm/migrations/diff.rb +337 -0
  40. data/lib/skyward/orm/migrations/directory.rb +48 -0
  41. data/lib/skyward/orm/migrations/discovery.rb +14 -0
  42. data/lib/skyward/orm/migrations/drop_column.rb +7 -0
  43. data/lib/skyward/orm/migrations/drop_constraint.rb +7 -0
  44. data/lib/skyward/orm/migrations/drop_index.rb +7 -0
  45. data/lib/skyward/orm/migrations/rename_column.rb +8 -0
  46. data/lib/skyward/orm/migrations/rename_constraint.rb +8 -0
  47. data/lib/skyward/orm/migrations/runner/edited.rb +7 -0
  48. data/lib/skyward/orm/migrations/runner/failed.rb +8 -0
  49. data/lib/skyward/orm/migrations/runner/irreversible.rb +7 -0
  50. data/lib/skyward/orm/migrations/runner/locked.rb +8 -0
  51. data/lib/skyward/orm/migrations/runner/migration.rb +11 -0
  52. data/lib/skyward/orm/migrations/runner/missing.rb +7 -0
  53. data/lib/skyward/orm/migrations/runner/raced.rb +7 -0
  54. data/lib/skyward/orm/migrations/runner.rb +237 -0
  55. data/lib/skyward/orm/migrations/script.rb +390 -0
  56. data/lib/skyward/orm/migrations/status.rb +122 -0
  57. data/lib/skyward/orm/migrations/summary.rb +107 -0
  58. data/lib/skyward/orm/migrations/versions.rb +19 -0
  59. data/lib/skyward/orm/migrations.rb +8 -0
  60. data/lib/skyward/orm/pool_timeout.rb +4 -0
  61. data/lib/skyward/orm/projection.rb +86 -0
  62. data/lib/skyward/orm/queries/clauses.rb +673 -0
  63. data/lib/skyward/orm/queries.rb +4 -0
  64. data/lib/skyward/orm/query.rb +26 -0
  65. data/lib/skyward/orm/record.rb +118 -0
  66. data/lib/skyward/orm/schema_mismatch.rb +4 -0
  67. data/lib/skyward/orm/statements/placeholders.rb +37 -0
  68. data/lib/skyward/orm/statements.rb +238 -0
  69. data/lib/skyward/orm/tables/check.rb +8 -0
  70. data/lib/skyward/orm/tables/column.rb +11 -0
  71. data/lib/skyward/orm/tables/column_types.rb +121 -0
  72. data/lib/skyward/orm/tables/declarations.rb +200 -0
  73. data/lib/skyward/orm/tables/length.rb +8 -0
  74. data/lib/skyward/orm/tables/loaded.rb +21 -0
  75. data/lib/skyward/orm/tables/members.rb +16 -0
  76. data/lib/skyward/orm/tables/reference.rb +9 -0
  77. data/lib/skyward/orm/tables/rows.rb +52 -0
  78. data/lib/skyward/orm/tables/schema.rb +14 -0
  79. data/lib/skyward/orm/tables/sources.rb +63 -0
  80. data/lib/skyward/orm/tables/sql.rb +7 -0
  81. data/lib/skyward/orm/tables/validation.rb +38 -0
  82. data/lib/skyward/orm/tables/values.rb +212 -0
  83. data/lib/skyward/orm/tables.rb +8 -0
  84. data/lib/skyward/orm/transactional.rb +18 -0
  85. data/lib/skyward/orm/version.rb +1 -1
  86. data/lib/skyward/orm/violation.rb +13 -0
  87. data/lib/skyward/orm/violation_error.rb +13 -0
  88. data/lib/skyward/orm.rb +106 -1
  89. data/sig/generated/skyward/orm/adapters/postgresql/connection.rbs +41 -0
  90. data/sig/generated/skyward/orm/adapters/postgresql.rbs +177 -0
  91. data/sig/generated/skyward/orm/adapters/sqlite/constraints.rbs +93 -0
  92. data/sig/generated/skyward/orm/adapters/sqlite.rbs +226 -0
  93. data/sig/generated/skyward/orm/adapters.rbs +18 -0
  94. data/sig/generated/skyward/orm/catalog/column.rbs +22 -0
  95. data/sig/generated/skyward/orm/catalog/constraint.rbs +22 -0
  96. data/sig/generated/skyward/orm/catalog/index.rbs +20 -0
  97. data/sig/generated/skyward/orm/catalog/table.rbs +20 -0
  98. data/sig/generated/skyward/orm/catalog.rbs +5 -0
  99. data/sig/generated/skyward/orm/cli/boot_file.rbs +21 -0
  100. data/sig/generated/skyward/orm/cli/migrate.rbs +15 -0
  101. data/sig/generated/skyward/orm/cli/migration.rbs +45 -0
  102. data/sig/generated/skyward/orm/cli/rollback.rbs +7 -0
  103. data/sig/generated/skyward/orm/cli/scaffold/source.rbs +147 -0
  104. data/sig/generated/skyward/orm/cli/scaffold.rbs +28 -0
  105. data/sig/generated/skyward/orm/cli/status.rbs +17 -0
  106. data/sig/generated/skyward/orm/cli.rbs +4 -0
  107. data/sig/generated/skyward/orm/commands.rbs +2 -0
  108. data/sig/generated/skyward/orm/connection/instrumented.rbs +45 -0
  109. data/sig/generated/skyward/orm/connection/pool.rbs +54 -0
  110. data/sig/generated/skyward/orm/connection/session.rbs +59 -0
  111. data/sig/generated/skyward/orm/connection.rbs +7 -0
  112. data/sig/generated/skyward/orm/database/schema_check.rbs +38 -0
  113. data/sig/generated/skyward/orm/database.rbs +225 -0
  114. data/sig/generated/skyward/orm/execution.rbs +18 -0
  115. data/sig/generated/skyward/orm/migration_error.rbs +4 -0
  116. data/sig/generated/skyward/orm/migrations/add_column.rbs +14 -0
  117. data/sig/generated/skyward/orm/migrations/add_constraint.rbs +14 -0
  118. data/sig/generated/skyward/orm/migrations/add_index.rbs +14 -0
  119. data/sig/generated/skyward/orm/migrations/alter_table.rbs +28 -0
  120. data/sig/generated/skyward/orm/migrations/change_default.rbs +18 -0
  121. data/sig/generated/skyward/orm/migrations/change_nullable.rbs +16 -0
  122. data/sig/generated/skyward/orm/migrations/change_type.rbs +18 -0
  123. data/sig/generated/skyward/orm/migrations/create_table.rbs +16 -0
  124. data/sig/generated/skyward/orm/migrations/definitions.rbs +81 -0
  125. data/sig/generated/skyward/orm/migrations/diff.rbs +165 -0
  126. data/sig/generated/skyward/orm/migrations/directory.rbs +37 -0
  127. data/sig/generated/skyward/orm/migrations/discovery.rbs +9 -0
  128. data/sig/generated/skyward/orm/migrations/drop_column.rbs +14 -0
  129. data/sig/generated/skyward/orm/migrations/drop_constraint.rbs +14 -0
  130. data/sig/generated/skyward/orm/migrations/drop_index.rbs +14 -0
  131. data/sig/generated/skyward/orm/migrations/rename_column.rbs +16 -0
  132. data/sig/generated/skyward/orm/migrations/rename_constraint.rbs +16 -0
  133. data/sig/generated/skyward/orm/migrations/runner/edited.rbs +14 -0
  134. data/sig/generated/skyward/orm/migrations/runner/failed.rbs +16 -0
  135. data/sig/generated/skyward/orm/migrations/runner/irreversible.rbs +14 -0
  136. data/sig/generated/skyward/orm/migrations/runner/locked.rbs +16 -0
  137. data/sig/generated/skyward/orm/migrations/runner/migration.rbs +22 -0
  138. data/sig/generated/skyward/orm/migrations/runner/missing.rbs +14 -0
  139. data/sig/generated/skyward/orm/migrations/runner/raced.rbs +14 -0
  140. data/sig/generated/skyward/orm/migrations/runner.rbs +78 -0
  141. data/sig/generated/skyward/orm/migrations/script.rbs +185 -0
  142. data/sig/generated/skyward/orm/migrations/status.rbs +62 -0
  143. data/sig/generated/skyward/orm/migrations/summary.rbs +49 -0
  144. data/sig/generated/skyward/orm/migrations/versions.rbs +11 -0
  145. data/sig/generated/skyward/orm/migrations.rbs +7 -0
  146. data/sig/generated/skyward/orm/pool_timeout.rbs +4 -0
  147. data/sig/generated/skyward/orm/projection.rbs +50 -0
  148. data/sig/generated/skyward/orm/queries/clauses.rbs +403 -0
  149. data/sig/generated/skyward/orm/queries.rbs +4 -0
  150. data/sig/generated/skyward/orm/query.rbs +20 -0
  151. data/sig/generated/skyward/orm/record.rbs +88 -0
  152. data/sig/generated/skyward/orm/schema_mismatch.rbs +4 -0
  153. data/sig/generated/skyward/orm/statements/placeholders.rbs +21 -0
  154. data/sig/generated/skyward/orm/statements.rbs +131 -0
  155. data/sig/generated/skyward/orm/tables/check.rbs +16 -0
  156. data/sig/generated/skyward/orm/tables/column.rbs +22 -0
  157. data/sig/generated/skyward/orm/tables/column_types.rbs +53 -0
  158. data/sig/generated/skyward/orm/tables/declarations.rbs +101 -0
  159. data/sig/generated/skyward/orm/tables/length.rbs +16 -0
  160. data/sig/generated/skyward/orm/tables/loaded.rbs +14 -0
  161. data/sig/generated/skyward/orm/tables/members.rbs +9 -0
  162. data/sig/generated/skyward/orm/tables/reference.rbs +18 -0
  163. data/sig/generated/skyward/orm/tables/rows.rbs +24 -0
  164. data/sig/generated/skyward/orm/tables/schema.rbs +28 -0
  165. data/sig/generated/skyward/orm/tables/sources.rbs +32 -0
  166. data/sig/generated/skyward/orm/tables/sql.rbs +14 -0
  167. data/sig/generated/skyward/orm/tables/validation.rbs +9 -0
  168. data/sig/generated/skyward/orm/tables/values.rbs +89 -0
  169. data/sig/generated/skyward/orm/tables.rbs +9 -0
  170. data/sig/generated/skyward/orm/transactional.rbs +11 -0
  171. data/sig/generated/skyward/orm/violation.rbs +22 -0
  172. data/sig/generated/skyward/orm/violation_error.rbs +10 -0
  173. data/sig/generated/skyward/orm.rbs +29 -0
  174. data/sig/manual/pg.rbs +43 -0
  175. data/sig/manual/skyward/orm/adapters/postgresql.rbs +3 -0
  176. data/sig/manual/skyward/orm/adapters/sqlite/constraints.rbs +3 -0
  177. data/sig/manual/skyward/orm/adapters/sqlite.rbs +3 -0
  178. data/sig/manual/skyward/orm/adapters.rbs +3 -0
  179. data/sig/manual/skyward/orm/cli/boot_file.rbs +3 -0
  180. data/sig/manual/skyward/orm/cli/migrate.rbs +3 -0
  181. data/sig/manual/skyward/orm/cli/migration.rbs +3 -0
  182. data/sig/manual/skyward/orm/cli/rollback.rbs +3 -0
  183. data/sig/manual/skyward/orm/cli/scaffold/source.rbs +3 -0
  184. data/sig/manual/skyward/orm/cli/scaffold.rbs +3 -0
  185. data/sig/manual/skyward/orm/cli/status.rbs +3 -0
  186. data/sig/manual/skyward/orm/database/schema_check.rbs +3 -0
  187. data/sig/manual/skyward/orm/migrations/definitions.rbs +3 -0
  188. data/sig/manual/skyward/orm/migrations/diff.rbs +3 -0
  189. data/sig/manual/skyward/orm/migrations/directory.rbs +3 -0
  190. data/sig/manual/skyward/orm/migrations/discovery.rbs +3 -0
  191. data/sig/manual/skyward/orm/migrations/runner.rbs +3 -0
  192. data/sig/manual/skyward/orm/migrations/script.rbs +3 -0
  193. data/sig/manual/skyward/orm/migrations/status.rbs +3 -0
  194. data/sig/manual/skyward/orm/migrations/summary.rbs +3 -0
  195. data/sig/manual/skyward/orm/migrations/versions.rbs +3 -0
  196. data/sig/manual/skyward/orm/statements/placeholders.rbs +3 -0
  197. data/sig/manual/skyward/orm/statements.rbs +3 -0
  198. data/sig/manual/skyward/orm/tables/loaded.rbs +3 -0
  199. data/sig/manual/skyward/orm/tables/members.rbs +3 -0
  200. data/sig/manual/skyward/orm/tables/rows.rbs +3 -0
  201. data/sig/manual/skyward/orm/tables/sources.rbs +3 -0
  202. data/sig/manual/skyward/orm/tables/validation.rbs +3 -0
  203. data/sig/manual/skyward/orm/tables/values.rbs +3 -0
  204. data/sig/manual/skyward/orm.rbs +72 -0
  205. data/sig/manual/sqlite3.rbs +23 -0
  206. metadata +217 -3
@@ -0,0 +1,673 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Skyward::ORM::Query and Skyward::ORM::Projection differ only in what a write
4
+ # returns, so everything else is here.
5
+ # @rbs generic R
6
+ module Skyward::ORM::Queries::Clauses
7
+ include Enumerable #[R]
8
+
9
+ # @rbs!
10
+ # type direction = :asc | :desc
11
+ # type condition = Comparison | Fragment | Negation | Disjunction
12
+ # type scope = :all | :start | :narrowed
13
+ # type parts = [singleton(Skyward::ORM::Record), Array[Join], scope, Array[condition],
14
+ # Array[[Symbol, direction]], Array[Symbol], Integer?, Integer?]
15
+
16
+ DIRECTIONS = %i[asc desc].freeze #: Array[direction]
17
+
18
+ COUNT = Skyward::ORM::Tables::Column.new(
19
+ name: :count, type: :integer, nullable: false, symbols: [], element: nil
20
+ ) #: Skyward::ORM::Tables::Column
21
+
22
+ Comparison = Data.define(
23
+ :column, #: Symbol
24
+ :operator, #: String
25
+ :value #: untyped
26
+ )
27
+
28
+ Fragment = Data.define(
29
+ :sql, #: String
30
+ :values #: Array[untyped]
31
+ )
32
+
33
+ Negation = Data.define(
34
+ :conditions #: Array[condition]
35
+ )
36
+
37
+ Disjunction = Data.define(
38
+ :left, #: Array[condition]
39
+ :right #: Array[condition]
40
+ )
41
+
42
+ Join = Data.define(
43
+ :keyword, #: String
44
+ :table, #: singleton(Skyward::ORM::Record)
45
+ :on #: Hash[Symbol, Symbol]
46
+ )
47
+
48
+ # @rbs @table: singleton(Skyward::ORM::Record)
49
+ # @rbs @session: Skyward::ORM::Connection::Session
50
+ # @rbs @joins: Array[Join]
51
+ # @rbs @row: Class
52
+ # @rbs @expressions: Hash[Symbol, String]
53
+ # @rbs @scope: scope
54
+ # @rbs @conditions: Array[condition]
55
+ # @rbs @orders: Array[[Symbol, direction]]
56
+ # @rbs @groups: Array[Symbol]
57
+ # @rbs @limit: Integer?
58
+ # @rbs @offset: Integer?
59
+
60
+ # scope: is :all only for an explicit Todo.all, which may update or delete
61
+ # every row, and :narrowed once a where or exclude has been called, even
62
+ # with nothing, which an insert refuses.
63
+ # @rbs table: singleton(Skyward::ORM::Record)
64
+ # @rbs session: Skyward::ORM::Connection::Session
65
+ # @rbs joins: Array[Join]
66
+ # @rbs row: Class
67
+ # @rbs expressions: Hash[Symbol, String]
68
+ # @rbs scope: scope
69
+ # @rbs conditions: Array[condition]
70
+ # @rbs orders: Array[[Symbol, direction]]
71
+ # @rbs groups: Array[Symbol]
72
+ # @rbs limit: Integer?
73
+ # @rbs offset: Integer?
74
+ # @rbs return: void
75
+ def initialize(
76
+ table,
77
+ session,
78
+ joins: [],
79
+ row: table,
80
+ expressions: {},
81
+ scope: :start,
82
+ conditions: [],
83
+ orders: [],
84
+ groups: [],
85
+ limit: nil,
86
+ offset: nil
87
+ )
88
+ @table = table
89
+ @session = session
90
+ @joins = [*joins].freeze
91
+ @row = row
92
+ @expressions = expressions.dup.freeze
93
+ @scope = scope
94
+ @conditions = [*conditions].freeze
95
+ @orders = [*orders].freeze
96
+ @groups = [*groups].freeze
97
+ @limit = limit
98
+ @offset = offset
99
+ freeze
100
+ end
101
+
102
+ # @rbs table: singleton(Skyward::ORM::Record)
103
+ # @rbs **on: Symbol
104
+ # @rbs return: self
105
+ def join(table, **on) = with(joins: [*@joins, joined("JOIN", table, on)])
106
+
107
+ # @rbs table: singleton(Skyward::ORM::Record)
108
+ # @rbs **on: Symbol
109
+ # @rbs return: self
110
+ def left_join(table, **on) = with(joins: [*@joins, joined("LEFT JOIN", table, on)])
111
+
112
+ # @rbs sql: String?
113
+ # @rbs *values: untyped
114
+ # @rbs **conditions: untyped
115
+ # @rbs return: self
116
+ def where(sql = nil, *values, **conditions)
117
+ with(scope: :narrowed, conditions: [*@conditions, *build(sql, values, conditions)])
118
+ end
119
+
120
+ # @rbs sql: String?
121
+ # @rbs *values: untyped
122
+ # @rbs **conditions: untyped
123
+ # @rbs return: self
124
+ def exclude(sql = nil, *values, **conditions)
125
+ built = build(sql, values, conditions)
126
+ with(scope: :narrowed, conditions: built.empty? ? @conditions : [*@conditions, Negation.new(conditions: built)])
127
+ end
128
+
129
+ # @rbs sql: String?
130
+ # @rbs *values: untyped
131
+ # @rbs **conditions: untyped
132
+ # @rbs return: self
133
+ def or(sql = nil, *values, **conditions)
134
+ raise ArgumentError, "#{@table} has no conditions to or with. Start with where or exclude." if @conditions.empty?
135
+
136
+ built = build(sql, values, conditions)
137
+ raise ArgumentError, "#{@table} has nothing to or with. Give or conditions or SQL." if built.empty?
138
+
139
+ with(conditions: [Disjunction.new(left: @conditions, right: built)])
140
+ end
141
+
142
+ # @rbs *columns: Symbol
143
+ # @rbs **directions: direction
144
+ # @rbs return: self
145
+ def order(*columns, **directions)
146
+ Skyward::ORM::Statements.require_columns(@table, [*columns, *directions.keys])
147
+ # The direction is written into the SQL, so only these two may reach it.
148
+ column, direction = directions.find { |_, candidate| !DIRECTIONS.include?(candidate) }
149
+ raise ArgumentError, "#{@table} can't order #{column} by #{direction.inspect}, only :asc or :desc" if column
150
+
151
+ with(orders: [*@orders, *columns.map { |name| [name, :asc] }, *directions.to_a])
152
+ end
153
+
154
+ # @rbs *columns: Symbol
155
+ # @rbs return: self
156
+ def group(*columns)
157
+ Skyward::ORM::Statements.require_columns(@table, columns)
158
+ with(groups: [*@groups, *columns])
159
+ end
160
+
161
+ # @rbs count: Integer
162
+ # @rbs return: self
163
+ def limit(count) = with(limit: require_count(:limit, count))
164
+
165
+ # @rbs count: Integer
166
+ # @rbs return: self
167
+ def offset(count) = with(offset: require_count(:offset, count))
168
+
169
+ # @rbs other: Skyward::ORM::Query[untyped]
170
+ # @rbs return: self
171
+ def merge(other)
172
+ require_query(other)
173
+ table, joins, scope, conditions, orders, groups, limit, offset = other.parts
174
+ raise ArgumentError, "#{@table} can't merge a query of #{table}, a different table class" unless table == @table
175
+
176
+ with(
177
+ joins: merged_joins(joins),
178
+ scope: merged_scope(scope),
179
+ conditions: [*@conditions, *conditions],
180
+ orders: [*@orders, *orders],
181
+ groups: [*@groups, *groups],
182
+ limit: limit || @limit,
183
+ offset: offset || @offset
184
+ )
185
+ end
186
+
187
+ # Steep ties the row class to S only through its new, so the query keeps it
188
+ # as the Class it is.
189
+ # @rbs [S] (Skyward::ORM::_Row[S] row, **String expressions) -> Skyward::ORM::Projection[S]
190
+ def into(row, **expressions)
191
+ klass = row #: Class
192
+ require_members(klass, expressions)
193
+ with(query: Skyward::ORM::Projection, row: klass, expressions:)
194
+ end
195
+
196
+ # Ordered by the primary key when nothing else orders it, so both databases
197
+ # return the same row.
198
+ # @rbs () -> R?
199
+ # | (Integer count) -> Array[R]
200
+ def first(count = nil)
201
+ return super if count
202
+
203
+ rows(@orders.empty? ? [[@table.schema.primary_key, :asc]] : @orders, 1).first
204
+ end
205
+
206
+ # @rbs **conditions: untyped
207
+ # @rbs return: R?
208
+ def find_by(**conditions) = where(**conditions).first
209
+
210
+ # PostgreSQL refuses an ORDER BY beside COUNT(*), so the count leaves it out.
211
+ # A LIMIT beside it would limit the one row COUNT(*) returns, so a page is
212
+ # counted through a subquery, as the groups of a grouped query are.
213
+ # @rbs (*untyped args) ?{ (R) -> boolish } -> Integer
214
+ def count(*args, &block)
215
+ return super if block || !args.empty?
216
+
217
+ database = @session.database
218
+ prepare(database)
219
+ sql, binds = from(database, [], @limit)
220
+ counted = @groups.empty? && @limit.nil? && @offset.nil? ? sql : %(FROM (SELECT 1 #{sql}) AS "counted")
221
+ # PostgreSQL's driver returns every value as text, so the adapter reads it.
222
+ database.adapter.decode(COUNT, database.execute("SELECT COUNT(*) #{counted}", binds).fetch(0).fetch(0))
223
+ end
224
+
225
+ # Order can't change whether the query has a row, so it's left out, and a
226
+ # limit of 0 has none.
227
+ # @rbs return: bool
228
+ def exists?
229
+ database = @session.database
230
+ prepare(database)
231
+ sql, binds = from(database, [], [@limit, 1].compact.min)
232
+ !database.execute("SELECT 1 #{sql}", binds).empty?
233
+ end
234
+
235
+ # @rbs () { (R) -> void } -> self
236
+ # | () -> Enumerator[R, self]
237
+ def each(&block)
238
+ return enum_for(:each) unless block
239
+
240
+ rows(@orders, @limit).each(&block)
241
+ self
242
+ end
243
+
244
+ # @rbs return: [String, Array[untyped]]
245
+ def to_sql = statement(@session.database, @orders, @limit)
246
+
247
+ protected
248
+
249
+ # rbs-inline writes a protected method as public, so Steep would let an app
250
+ # call this, though Ruby won't.
251
+ # @rbs return: parts
252
+ def parts = [@table, @joins, @scope, @conditions, @orders, @groups, @limit, @offset]
253
+
254
+ private
255
+
256
+ # Steep can't tie the class it builds to self, or the row class to S, so
257
+ # each public method types the query it returns.
258
+ # @rbs query: Class
259
+ # @rbs joins: Array[Join]
260
+ # @rbs row: Class
261
+ # @rbs expressions: Hash[Symbol, String]
262
+ # @rbs scope: scope
263
+ # @rbs conditions: Array[condition]
264
+ # @rbs orders: Array[[Symbol, direction]]
265
+ # @rbs groups: Array[Symbol]
266
+ # @rbs limit: Integer?
267
+ # @rbs offset: Integer?
268
+ # @rbs return: untyped
269
+ def with(
270
+ # Steep reads self.class in a module as the module, though it's always the
271
+ # class that includes it.
272
+ query: self.class, # steep:ignore IncompatibleAssignment
273
+ joins: @joins,
274
+ row: @row,
275
+ expressions: @expressions,
276
+ scope: @scope,
277
+ conditions: @conditions,
278
+ orders: @orders,
279
+ groups: @groups,
280
+ limit: @limit,
281
+ offset: @offset
282
+ )
283
+ query.new(@table, @session, joins:, row:, expressions:, scope:, conditions:, orders:, groups:, limit:, offset:)
284
+ end
285
+
286
+ # @rbs keyword: String
287
+ # @rbs table: singleton(Skyward::ORM::Record)
288
+ # @rbs on: Hash[Symbol, Symbol]
289
+ # @rbs return: Join
290
+ def joined(keyword, table, on)
291
+ unless table.is_a?(Class) && table < Skyward::ORM::Record && table.schema.table
292
+ raise ArgumentError, "#{@table} can't join #{table.inspect}, which isn't a table class"
293
+ end
294
+ if present?(table)
295
+ raise ArgumentError, "#{@table} can't join #{table}, since #{table.table_name} is already in the query"
296
+ end
297
+ raise ArgumentError, "#{@table} can't join #{table} on nothing. Give it columns, such as list_id: :id" if on.empty?
298
+
299
+ Skyward::ORM::Statements.require_columns(@table, on.keys)
300
+ Skyward::ORM::Statements.require_columns(table, on.values)
301
+ Join.new(keyword:, table:, on:)
302
+ end
303
+
304
+ # @rbs other: untyped
305
+ # @rbs return: void
306
+ def require_query(other)
307
+ if other.is_a?(Skyward::ORM::Projection)
308
+ raise ArgumentError,
309
+ "#{@table} can't merge a projection, whose row class and expressions would have nowhere to go. " \
310
+ "Merge the query before its into."
311
+ end
312
+ return if other.is_a?(Skyward::ORM::Query)
313
+
314
+ raise ArgumentError, "#{@table} can't merge #{other.inspect}, which isn't a query"
315
+ end
316
+
317
+ # Two scopes that each join a table the same way compose, so an identical
318
+ # join is kept once.
319
+ # @rbs joins: Array[Join]
320
+ # @rbs return: Array[Join]
321
+ def merged_joins(joins)
322
+ added = joins - @joins
323
+ conflict = added.find { |join| present?(join.table) }
324
+ if conflict
325
+ raise ArgumentError,
326
+ "#{@table} can't merge a different join of #{conflict.table}, " \
327
+ "since #{conflict.table.table_name} is already in the query"
328
+ end
329
+
330
+ [*@joins, *added]
331
+ end
332
+
333
+ # Merging only ever narrows, so every row may be changed only when both
334
+ # queries said so with an explicit all.
335
+ # @rbs scope: scope
336
+ # @rbs return: scope
337
+ def merged_scope(scope)
338
+ return :narrowed if [@scope, scope].include?(:narrowed)
339
+
340
+ @scope == :all && scope == :all ? :all : :start
341
+ end
342
+
343
+ # @rbs sql: String?
344
+ # @rbs values: Array[untyped]
345
+ # @rbs conditions: Hash[Symbol, untyped]
346
+ # @rbs return: Array[condition]
347
+ def build(sql, values, conditions)
348
+ Skyward::ORM::Statements.require_conditions(@session.database.column_types, @table, conditions)
349
+ [(Fragment.new(sql:, values:) if sql), *conditions.flat_map { |column, value| comparisons(column, value) }].compact
350
+ end
351
+
352
+ # @rbs column: Symbol
353
+ # @rbs value: untyped
354
+ # @rbs return: Array[Comparison]
355
+ def comparisons(column, value)
356
+ return [Comparison.new(column:, operator: "=", value:)] unless value.is_a?(Range)
357
+
358
+ ends = [
359
+ (Comparison.new(column:, operator: ">=", value: value.begin) unless value.begin.nil?),
360
+ (Comparison.new(column:, operator: value.exclude_end? ? "<" : "<=", value: value.end) unless value.end.nil?)
361
+ ].compact
362
+ raise ArgumentError, "#{@table} can't match #{column} to #{value.inspect}, a range with neither end" if ends.empty?
363
+
364
+ ends
365
+ end
366
+
367
+ # @rbs return: Array[String]
368
+ def clauses
369
+ [
370
+ ("into expressions" unless @expressions.empty?),
371
+ ("join" unless @joins.empty?),
372
+ ("order" unless @orders.empty?),
373
+ ("group" unless @groups.empty?),
374
+ ("limit" if @limit),
375
+ ("offset" if @offset)
376
+ ].compact
377
+ end
378
+
379
+ # @rbs clauses: Array[String]
380
+ # @rbs return: String
381
+ def listing(clauses)
382
+ *others, last = clauses
383
+ others.empty? ? last.to_s : "#{others.join(", ")} or #{last}"
384
+ end
385
+
386
+ # Neither PostgreSQL nor SQLite (as it's usually built) takes a JOIN,
387
+ # ORDER BY, GROUP BY, LIMIT or OFFSET on an UPDATE or DELETE, and an into
388
+ # expression, such as an aggregate, means nothing portable in its RETURNING.
389
+ # @rbs method: Symbol
390
+ # @rbs return: void
391
+ def require_writable(method)
392
+ refused = clauses
393
+ unless refused.empty?
394
+ raise ArgumentError,
395
+ "#{@table} can't #{method} a query with #{listing(refused)}, which PostgreSQL and SQLite don't both support"
396
+ end
397
+ return unless @conditions.empty? && @scope != :all
398
+
399
+ raise ArgumentError,
400
+ "#{@table} can't #{method} a query with no conditions, which would change every row. " \
401
+ "Narrow it with where or exclude, or start from #{@table}.all to change every row."
402
+ end
403
+
404
+ # @rbs method: Symbol
405
+ # @rbs count: Integer
406
+ # @rbs return: Integer
407
+ def require_count(method, count)
408
+ return count if count.is_a?(Integer) && !count.negative?
409
+
410
+ raise ArgumentError, "#{@table} can't #{method} by #{count.inspect}, only by a non-negative Integer"
411
+ end
412
+
413
+ # @rbs row: Class
414
+ # @rbs expressions: Hash[Symbol, String]
415
+ # @rbs return: void
416
+ def require_members(row, expressions)
417
+ members = Skyward::ORM::Tables::Members.of(row)
418
+ unknown = expressions.keys - members
419
+ raise ArgumentError, "#{row} has no member #{unknown.join(", ")} to take an expression" unless unknown.empty?
420
+
421
+ unread = members - @table.schema.columns - expressions.keys
422
+ return if unread.empty?
423
+
424
+ raise ArgumentError, "#{@table} has no column #{unread.join(", ")}, so #{row} needs an expression for it"
425
+ end
426
+
427
+ # @rbs database: Skyward::ORM::Database
428
+ # @rbs orders: Array[[Symbol, direction]]
429
+ # @rbs limit: Integer?
430
+ # @rbs return: [String, Array[untyped]]
431
+ def statement(database, orders, limit)
432
+ sql, binds = from(database, orders, limit)
433
+ columns = Skyward::ORM::Tables::Members.of(@row).map do |member|
434
+ expression = @expressions.fetch(member, nil)
435
+ expression ? "#{expression} AS #{Skyward::ORM::Statements.quote(member)}" : qualified(member)
436
+ end.join(", ")
437
+ ["SELECT #{columns} #{sql}", binds]
438
+ end
439
+
440
+ # @rbs database: Skyward::ORM::Database
441
+ # @rbs orders: Array[[Symbol, direction]]
442
+ # @rbs limit: Integer?
443
+ # @rbs return: [String, Array[untyped]]
444
+ def from(database, orders, limit)
445
+ adapter = database.adapter
446
+ where, binds = filter(database, 1)
447
+ columns = Skyward::ORM::Statements.by_name(database.column_types, @table)
448
+ ordered = orders.map do |column, direction|
449
+ "#{adapter.comparable(columns[column]&.type || :untyped, qualified(column))} #{direction.upcase}"
450
+ end
451
+ # The limit and offset are bound rather than written in, so every page of a
452
+ # query shares one SQL string.
453
+ paging = [limit, @offset].compact
454
+ sql = [
455
+ "FROM #{Skyward::ORM::Statements.quote(@table.table_name)}",
456
+ *@joins.map { |join| joining(join) },
457
+ where,
458
+ ("GROUP BY #{@groups.map { |column| qualified(column) }.join(", ")}" unless @groups.empty?),
459
+ ("ORDER BY #{ordered.join(", ")}" unless orders.empty?),
460
+ limit ? "LIMIT #{adapter.placeholder(binds.size + 1)}" : (adapter.unlimited if @offset),
461
+ ("OFFSET #{adapter.placeholder(binds.size + paging.size)}" if @offset)
462
+ ].compact.join(" ")
463
+ [sql, [*binds, *paging]]
464
+ end
465
+
466
+ # @rbs join: Join
467
+ # @rbs return: String
468
+ def joining(join)
469
+ on = join.on.map { |column, joined| "#{qualified(column)} = #{qualified(joined, join.table)}" }.join(" AND ")
470
+ "#{join.keyword} #{Skyward::ORM::Statements.quote(join.table.table_name)} ON #{on}"
471
+ end
472
+
473
+ # An UPDATE binds its SET values first, so its WHERE's numbered placeholders
474
+ # start after them.
475
+ # @rbs database: Skyward::ORM::Database
476
+ # @rbs position: Integer
477
+ # @rbs return: [String?, Array[untyped]]
478
+ def filter(database, position)
479
+ clauses, binds = conjunction(database, @conditions, position)
480
+ [("WHERE #{clauses}" unless @conditions.empty?), binds]
481
+ end
482
+
483
+ # @rbs database: Skyward::ORM::Database
484
+ # @rbs conditions: Array[condition]
485
+ # @rbs position: Integer
486
+ # @rbs return: [String, Array[untyped]]
487
+ def conjunction(database, conditions, position)
488
+ none = [[], []] #: [Array[String], Array[untyped]]
489
+ clauses, binds = conditions.reduce(none) do |(sqls, values), condition|
490
+ sql, bound = render(database, condition, position + values.size)
491
+ [[*sqls, condition.is_a?(Disjunction) && conditions.size > 1 ? "(#{sql})" : sql], [*values, *bound]]
492
+ end
493
+ [clauses.join(" AND "), binds]
494
+ end
495
+
496
+ # @rbs database: Skyward::ORM::Database
497
+ # @rbs condition: condition
498
+ # @rbs position: Integer
499
+ # @rbs return: [String, Array[untyped]]
500
+ def render(database, condition, position)
501
+ case condition
502
+ when Comparison then comparison(database, condition, position)
503
+ when Fragment then fragment(database, condition, position)
504
+ when Negation then negation(database, condition.conditions, position)
505
+ when Disjunction
506
+ left, left_binds = alternative(database, condition.left, position)
507
+ right, right_binds = alternative(database, condition.right, position + left_binds.size)
508
+ ["#{left} OR #{right}", [*left_binds, *right_binds]]
509
+ end
510
+ end
511
+
512
+ # @rbs database: Skyward::ORM::Database
513
+ # @rbs comparison: Comparison
514
+ # @rbs position: Integer
515
+ # @rbs return: [String, Array[untyped]]
516
+ def comparison(database, comparison, position)
517
+ adapter = database.adapter
518
+ column = Skyward::ORM::Statements.by_name(database.column_types, @table).fetch(comparison.column)
519
+ name = qualified(comparison.column)
520
+ value = comparison.value
521
+ case value
522
+ when nil then ["#{name} IS NULL", []]
523
+ when Array then within(adapter, column, name, value, position)
524
+ else
525
+ # = compares exactly as the column stores its values, and only a range's
526
+ # ends need them in order.
527
+ compared = comparison.operator == "=" ? name : adapter.comparable(column.type, name)
528
+ bound = Skyward::ORM::Statements.encode(adapter, column, value)
529
+ ["#{compared} #{comparison.operator} #{adapter.placeholder(position)}", [bound]]
530
+ end
531
+ end
532
+
533
+ # @rbs database: Skyward::ORM::Database
534
+ # @rbs fragment: Fragment
535
+ # @rbs position: Integer
536
+ # @rbs return: [String, Array[untyped]]
537
+ def fragment(database, fragment, position)
538
+ adapter = database.adapter
539
+ binds = fragment.values.map { |value| adapter.encode(value) }
540
+ Skyward::ORM::Statements::Placeholders.require_scalars(binds, "An SQL condition")
541
+ sql = Skyward::ORM::Statements::Placeholders.replace(fragment.sql, binds.size) do |index|
542
+ adapter.placeholder(position + index - 1)
543
+ end
544
+ # A -- comment runs to the end of its line, so the closing parenthesis
545
+ # goes on a line of its own.
546
+ ["(#{sql}#{"\n" if sql.include?("--")})", binds]
547
+ end
548
+
549
+ # NOT of an unknown is unknown, so a row whose column is NULL would be left
550
+ # out, though it doesn't match. An untyped column may hold NULL, and an SQL
551
+ # string's columns can't be known.
552
+ # @rbs database: Skyward::ORM::Database
553
+ # @rbs conditions: Array[condition]
554
+ # @rbs position: Integer
555
+ # @rbs return: [String, Array[untyped]]
556
+ def negation(database, conditions, position)
557
+ sql, binds = conjunction(database, conditions, position)
558
+ nullable = database.column_types.columns(@table).select { |column| column.nullable || column.type == :untyped }
559
+ .map(&:name)
560
+ unknowable = conditions.filter_map do |condition|
561
+ next unless condition.is_a?(Comparison) && nullable.include?(condition.column)
562
+
563
+ value = condition.value
564
+ condition.column unless value.nil? || (value.is_a?(Array) && value.include?(nil))
565
+ end
566
+ kept = unknowable.uniq.map { |column| " OR #{qualified(column)} IS NULL" }.join
567
+ [kept.empty? ? "NOT (#{sql})" : "(NOT (#{sql})#{kept})", binds]
568
+ end
569
+
570
+ # @rbs database: Skyward::ORM::Database
571
+ # @rbs conditions: Array[condition]
572
+ # @rbs position: Integer
573
+ # @rbs return: [String, Array[untyped]]
574
+ def alternative(database, conditions, position)
575
+ sql, binds = conjunction(database, conditions, position)
576
+ [conditions.size > 1 ? "(#{sql})" : sql, binds]
577
+ end
578
+
579
+ # PostgreSQL refuses an empty IN (), and IN never matches NULL.
580
+ # @rbs adapter: Skyward::ORM::_Adapter
581
+ # @rbs column: Skyward::ORM::Tables::Column
582
+ # @rbs name: String
583
+ # @rbs values: Array[untyped]
584
+ # @rbs position: Integer
585
+ # @rbs return: [String, Array[untyped]]
586
+ def within(adapter, column, name, values, position)
587
+ present = values.compact
588
+ placeholders = Array.new(present.size) { |index| adapter.placeholder(position + index) }
589
+ list = "#{name} IN (#{placeholders.join(", ")})"
590
+ sql = if values.empty? then "1 = 0"
591
+ elsif present.empty? then "#{name} IS NULL"
592
+ elsif values.include?(nil) then "(#{list} OR #{name} IS NULL)"
593
+ else list
594
+ end
595
+ [sql, present.map { |value| Skyward::ORM::Statements.encode(adapter, column, value) }]
596
+ end
597
+
598
+ # Steep can't tie the row class to R, so the rows are untyped here and each
599
+ # public method types them.
600
+ # @rbs orders: Array[[Symbol, direction]]
601
+ # @rbs limit: Integer?
602
+ # @rbs return: Array[untyped]
603
+ def rows(orders, limit)
604
+ database = @session.database
605
+ # Building the decoder prepares the starting table, once.
606
+ @joins.each { |join| database.prepare(join.table) }
607
+ decode = database.decoder(@table, @row, @expressions.keys)
608
+ sql, binds = statement(database, orders, limit)
609
+ database.execute(sql, binds).map(&decode)
610
+ end
611
+
612
+ # @rbs return: Array[singleton(Skyward::ORM::Record)]
613
+ def tables = [@table, *@joins.map(&:table)]
614
+
615
+ # A table that's in a query twice needs an alias to tell the two apart,
616
+ # which a query can't give it.
617
+ # @rbs table: singleton(Skyward::ORM::Record)
618
+ # @rbs return: bool
619
+ def present?(table) = tables.any? { |present| present.table_name == table.table_name }
620
+
621
+ # @rbs database: Skyward::ORM::Database
622
+ # @rbs return: void
623
+ def prepare(database) = tables.each { |table| database.prepare(table) }
624
+
625
+ # Once a query has a join, a column's name could be in more than one table,
626
+ # so each is qualified with its own.
627
+ # @rbs name: Symbol
628
+ # @rbs table: singleton(Skyward::ORM::Record)
629
+ # @rbs return: String
630
+ def qualified(name, table = @table)
631
+ quoted = Skyward::ORM::Statements.quote(name)
632
+ @joins.empty? ? quoted : "#{Skyward::ORM::Statements.quote(table.table_name)}.#{quoted}"
633
+ end
634
+
635
+ # @rbs values: Hash[Symbol, untyped]
636
+ # @rbs return: [String, Array[untyped]]
637
+ def updating(values)
638
+ raise ArgumentError, "#{@table} update needs a column to set, such as update(done: true)" if values.empty?
639
+
640
+ database = @session.database
641
+ column_types = database.column_types
642
+ Skyward::ORM::Statements.require_values(column_types, database.tables, @table, values)
643
+ assignments = values.keys.each.with_index(1).map do |column, position|
644
+ "#{Skyward::ORM::Statements.quote(column)} = #{database.adapter.placeholder(position)}"
645
+ end
646
+ changing(
647
+ :update,
648
+ "UPDATE #{Skyward::ORM::Statements.quote(@table.table_name)} SET #{assignments.join(", ")}",
649
+ Skyward::ORM::Statements.binds(database.adapter, column_types, @table, values)
650
+ )
651
+ end
652
+
653
+ # @rbs return: [String, Array[untyped]]
654
+ def deleting = changing(:delete, "DELETE FROM #{Skyward::ORM::Statements.quote(@table.table_name)}", [])
655
+
656
+ # @rbs method: Symbol
657
+ # @rbs sql: String
658
+ # @rbs set: Array[untyped]
659
+ # @rbs return: [String, Array[untyped]]
660
+ def changing(method, sql, set)
661
+ require_writable(method)
662
+ where, binds = filter(@session.database, set.size + 1)
663
+ [[sql, where].compact.join(" "), [*set, *binds]]
664
+ end
665
+
666
+ # @rbs [T] (T | Skyward::ORM::Violation written) -> T
667
+ def unviolated(written)
668
+ case written
669
+ when Skyward::ORM::Violation then raise Skyward::ORM::ViolationError, written
670
+ else written
671
+ end
672
+ end
673
+ end
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Skyward::ORM::Queries
4
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ # @rbs generic R
4
+ class Skyward::ORM::Query
5
+ include Skyward::ORM::Queries::Clauses #[R]
6
+
7
+ # @rbs **values: untyped
8
+ # @rbs return: Integer | Skyward::ORM::Violation
9
+ def update(**values)
10
+ sql, binds = updating(values)
11
+ @session.database.write(@table, sql, binds)
12
+ end
13
+
14
+ # @rbs **values: untyped
15
+ # @rbs return: Integer
16
+ def update!(**values) = unviolated(update(**values))
17
+
18
+ # @rbs return: Integer | Skyward::ORM::Violation
19
+ def delete
20
+ sql, binds = deleting
21
+ @session.database.write(@table, sql, binds)
22
+ end
23
+
24
+ # @rbs return: Integer
25
+ def delete! = unviolated(delete)
26
+ end