active_record-async_connection_pool 0.1.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 (24) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.md +349 -0
  4. data/Rakefile +11 -0
  5. data/lib/active_record/async_connection_pool/adapter_extension/attachment.rb +276 -0
  6. data/lib/active_record/async_connection_pool/adapter_extension/detection.rb +55 -0
  7. data/lib/active_record/async_connection_pool/adapter_extension.rb +343 -0
  8. data/lib/active_record/async_connection_pool/database_options.rb +80 -0
  9. data/lib/active_record/async_connection_pool/errors.rb +17 -0
  10. data/lib/active_record/async_connection_pool/handler.rb +183 -0
  11. data/lib/active_record/async_connection_pool/handlers/postgresql/adapter_methods.rb +216 -0
  12. data/lib/active_record/async_connection_pool/handlers/postgresql/pg_query_detector.rb +256 -0
  13. data/lib/active_record/async_connection_pool/handlers/postgresql.rb +347 -0
  14. data/lib/active_record/async_connection_pool/handlers/sqlite3/adapter_methods.rb +143 -0
  15. data/lib/active_record/async_connection_pool/handlers/sqlite3.rb +183 -0
  16. data/lib/active_record/async_connection_pool/handlers/trilogy/adapter_methods.rb +140 -0
  17. data/lib/active_record/async_connection_pool/handlers/trilogy.rb +159 -0
  18. data/lib/active_record/async_connection_pool/pool_extension.rb +201 -0
  19. data/lib/active_record/async_connection_pool/raw_entry.rb +80 -0
  20. data/lib/active_record/async_connection_pool/raw_pool.rb +336 -0
  21. data/lib/active_record/async_connection_pool/session_state.rb +223 -0
  22. data/lib/active_record/async_connection_pool/version.rb +8 -0
  23. data/lib/active_record/async_connection_pool.rb +86 -0
  24. metadata +86 -0
@@ -0,0 +1,347 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ module ActiveRecord
5
+ module AsyncConnectionPool
6
+ module Handlers
7
+ # `pg` waits on sockets through the fiber scheduler, so queries yield. The adapter caches state that lives in
8
+ # the database session (prepared statements, the notice receiver, `search_path`, the timestamp decoder), so that
9
+ # state is kept per raw connection in `RawEntry#state` and handed to whichever adapter attaches:
10
+ #
11
+ # - `:statements`: the raw connection's statement pool, and `:generation`, the raw pool's statement generation
12
+ # it was last cleared under.
13
+ # - `:settings`: the session settings applied on the raw connection, and `:defaults`, those it was configured
14
+ # with. The adapter's own values are reconciled against them on attach.
15
+ # - `:mapped_default_timezone`, `:timestamp_decoder`, `:type_map_for_results`: the result decoding set up on the
16
+ # raw connection.
17
+ class PostgreSQL < Handler
18
+ # An applied setting whose value is not known, eg. one set inside a transaction that may roll back.
19
+ UNKNOWN = Object.new.freeze
20
+
21
+ # Every pattern below needs one of these words, so most statements skip lexing.
22
+ HINT = /set|listen|prepare|temp|pg_temp|declare|advisory|load|do|call|discard|deallocate/i
23
+
24
+ # Matched against the code view, where comments are a space, so `PREPARE/**/p` reads as `PREPARE p`.
25
+ #
26
+ # `DO` and `CALL` run server-side code, whose dollar-quoted body is blanked, so they count whatever they do
27
+ # (`SET`, `set_config(..., false)`, advisory locks, temp tables).
28
+ #
29
+ # An object created in `pg_temp` is a temp object, and `pg_temp` is searched first, so it would shadow a table
30
+ # of the same name for every fiber the raw connection serves next.
31
+ #
32
+ # Transaction-scoped forms (`SET LOCAL`, `pg_advisory_xact_lock`, `ON COMMIT DROP`, `set_config(..., true)`)
33
+ # end with the transaction, so they are not session state. `set_config` matches unless its third argument is
34
+ # the literal `true`.
35
+ #
36
+ # `DISCARD ALL` and `DEALLOCATE` clear state the raw connection's records still list (its statement pool, its
37
+ # settings), so the raw connection is reset to bring them back in line. Other `DISCARD`s and `UNLISTEN` only
38
+ # clear what was pinned when it was made.
39
+ SESSION_STATE_CODE_PATTERNS = [
40
+ /\ARESET\b/,
41
+ /\ALISTEN\b/,
42
+ /\APREPARE\s+(?!TRANSACTION\b)/,
43
+ /\ALOAD\b/,
44
+ /\ADISCARD\s+ALL\b/,
45
+ /\ADEALLOCATE\b/,
46
+ /\ASET\s+(?!(?:LOCAL|TRANSACTION|CONSTRAINTS)\b(?!\s*\.))/,
47
+ /\A(?:DO|CALL)\b/,
48
+ /\ACREATE\s+(?:OR\s+REPLACE\s+)?(?:(?:GLOBAL|LOCAL)\s+)?TEMP(?:ORARY)?\s(?!.*\bON\s+COMMIT\s+DROP\b)/m,
49
+ /\ACREATE\s+(?:\w+\s+)*?pg_temp\s*\.(?!.*\bON\s+COMMIT\s+DROP\b)/m,
50
+ /\A(?:SELECT|WITH)\b.*\bINTO\s+(?:(?:GLOBAL|LOCAL)\s+)?TEMP(?:ORARY)?\b/m,
51
+ /\A(?:SELECT|WITH)\b.*(?<!\bINSERT )\bINTO\s+(?:UNLOGGED\s+)?(?:TABLE\s+)?pg_temp\s*\./m,
52
+ /\ADECLARE\b.*?\bWITH\s+HOLD\b/m,
53
+ /\bpg_(?:try_)?advisory_lock(?:_shared)?\s*\(/,
54
+ /\bset_config\s*\((?![^,()]*,[^,()]*,\s*true\s*\))/,
55
+ ].freeze
56
+
57
+ class << self
58
+ # Appends a notice to the warnings of the adapter attached to the raw connection, as the receiver
59
+ # ActiveRecord installs does for the adapter that configured it. ActiveRecord installs its receiver only
60
+ # while `db_warnings_action` is set, and relies on reconnecting to install it once it is; a raw connection
61
+ # outlives the adapter's reconnects, so the action is checked here instead. Unset, the notice goes to
62
+ # stderr, as libpq's default receiver prints it.
63
+ #
64
+ #: (untyped adapter, untyped result) -> void
65
+ def route_notice(adapter, result) # :nodoc:
66
+ return $stderr.write(result.error_message) unless ActiveRecord.db_warnings_action # rubocop:disable Rails/Output
67
+ return unless adapter
68
+
69
+ warning = ActiveRecord::SQLWarning.new(
70
+ result.error_field(PG::Result::PG_DIAG_MESSAGE_PRIMARY),
71
+ result.error_field(PG::Result::PG_DIAG_SQLSTATE),
72
+ result.error_field(PG::Result::PG_DIAG_SEVERITY),
73
+ nil,
74
+ adapter.pool
75
+ )
76
+ adapter.instance_variable_get(:@notice_receiver_sql_warnings) << warning
77
+ end
78
+
79
+ # The detector `postgresql_detector` resolves to: `:pg_query` or `:lexer`. Raises
80
+ # `DetectorUnavailableError` for `:pg_query` when the pg_query gem can't be loaded.
81
+ #
82
+ #: () -> Symbol
83
+ def detector
84
+ case AsyncConnectionPool.postgresql_detector
85
+ when :lexer then :lexer
86
+ when :pg_query
87
+ PgQueryDetector.load!
88
+ :pg_query
89
+ else PgQueryDetector.available? ? :pg_query : :lexer
90
+ end
91
+ end
92
+ end
93
+
94
+ # Resolves the detector, so a missing pg_query is found when the pool is set up rather than on a query.
95
+ #
96
+ #: (ActiveRecord::DatabaseConfigurations::DatabaseConfig db_config, DatabaseOptions options) -> void
97
+ def initialize(db_config, options)
98
+ super
99
+ self.class.detector
100
+ end
101
+
102
+ #: () -> Symbol
103
+ def sql_dialect
104
+ :postgresql
105
+ end
106
+
107
+ #: () -> Array[Regexp | String]
108
+ def session_state_code_patterns
109
+ SESSION_STATE_CODE_PATTERNS
110
+ end
111
+
112
+ # The keyword prefilter applies to both detectors: every form either one detects needs one of its words.
113
+ #
114
+ #: (String sql) -> bool
115
+ def session_state_statement?(sql)
116
+ return false unless sql.match?(HINT)
117
+
118
+ self.class.detector == :pg_query ? PgQueryDetector.session_state?(sql) : super
119
+ end
120
+
121
+ # Hands the raw connection's session state to the adapter, then brings the session's settings in line with
122
+ # the adapter's. A raw connection not configured yet (`reconnect!`) only gets its statement pool:
123
+ # `configure_connection` follows and records the rest.
124
+ #
125
+ #: (untyped adapter, RawEntry entry) -> void
126
+ def adopt(adapter, entry)
127
+ take_configuration(adapter, entry)
128
+ adopt_statements(adapter, entry)
129
+ state = entry.state
130
+ return unless state.key?(:settings)
131
+
132
+ adapter.instance_variable_set(:@mapped_default_timezone, state[:mapped_default_timezone])
133
+ adapter.instance_variable_set(:@timestamp_decoder, state[:timestamp_decoder])
134
+ adapter.instance_variable_set(:@type_map_for_results, state[:type_map_for_results])
135
+ adapter.without_session_state_detection do
136
+ adapter.send(:async_pg_load_type_map) unless adapter.instance_variable_get(:@type_map)
137
+ reconcile(adapter, entry)
138
+ end
139
+ end
140
+
141
+ # The timezone the raw connection decodes timestamps in may have changed while attached.
142
+ #
143
+ #: (untyped adapter, RawEntry entry) -> void
144
+ def release(adapter, entry)
145
+ if entry.state.key?(:settings)
146
+ entry.state[:mapped_default_timezone] = adapter.instance_variable_get(:@mapped_default_timezone)
147
+ entry.state[:timestamp_decoder] = adapter.instance_variable_get(:@timestamp_decoder)
148
+ end
149
+ adapter.instance_variable_set(:@statements, nil)
150
+ end
151
+
152
+ # Called by the adapter after `configure_connection` runs on its attached raw connection.
153
+ #
154
+ #: (untyped adapter, RawEntry entry) -> void
155
+ def configured(adapter, entry) # :nodoc:
156
+ take_configuration(adapter, entry)
157
+ end
158
+
159
+ # What `configure_connection` left on the adapter's raw connection, read before the adapter's own values are
160
+ # restored. `variables:` are applied after the settings ActiveRecord caches, so a setting they name is read
161
+ # back from the session. `role` is not reconciled, but `SET SESSION AUTHORIZATION` resets it, so a configured
162
+ # one is kept to restore with the configured session user.
163
+ #
164
+ #: (untyped adapter) -> Hash[Symbol, untyped]
165
+ def configuration(adapter) # :nodoc:
166
+ config = adapter.instance_variable_get(:@config)
167
+ variables = config.fetch(:variables, {}).to_h.transform_keys { |name| name.to_s.downcase }
168
+ configured = lambda do |name, default|
169
+ variables.key?(name) ? adapter.send(:query_value, "SHOW #{name}", 'SCHEMA') : default
170
+ end
171
+ {
172
+ raw: adapter.instance_variable_get(:@raw_connection),
173
+ settings: {
174
+ session_auth: configured.call('session_authorization', nil),
175
+ search_path: configured.call('search_path', adapter.instance_variable_get(:@schema_search_path)),
176
+ client_min_messages: configured.call('client_min_messages', (config[:min_messages] || 'warning').to_s),
177
+ }.freeze,
178
+ role: configured.call('role', nil),
179
+ mapped_default_timezone: adapter.instance_variable_get(:@mapped_default_timezone),
180
+ timestamp_decoder: adapter.instance_variable_get(:@timestamp_decoder),
181
+ type_map_for_results: adapter.instance_variable_get(:@type_map_for_results),
182
+ }
183
+ end
184
+
185
+ # Applies a session setting through the adapter's setter, on its attached raw connection. Inside a transaction
186
+ # the value may roll back, so it is recorded as unknown and applied again on the next attach.
187
+ #
188
+ #: (untyped adapter, RawEntry entry, Symbol key, untyped value) -> void
189
+ def set_session(adapter, entry, key, value) # :nodoc:
190
+ settings = entry.state[:settings] ||= {}
191
+ return if settings.fetch(key, UNKNOWN) == value
192
+
193
+ apply(adapter, entry, key, value, materialize_transactions: true)
194
+ settings[key] = entry.raw.transaction_status == PG::PQTRANS_IDLE ? value : UNKNOWN
195
+ end
196
+
197
+ # `DISCARD ALL` clears every kind of session state (settings, prepared statements, temp tables, `LISTEN`,
198
+ # advisory locks, held cursors), then the adapter configures the connection again.
199
+ #
200
+ #: (untyped adapter, RawEntry entry) -> bool
201
+ def reset(adapter, entry) # rubocop:disable Naming/PredicateMethod
202
+ raw = entry.raw
203
+ return false if raw.finished? || raw.transaction_status != PG::PQTRANS_IDLE
204
+
205
+ adapter.without_session_state_detection do
206
+ adapter.send(:internal_execute, 'DISCARD ALL', 'SCHEMA', materialize_transactions: false)
207
+ entry.state.delete(:settings)
208
+ entry.state[:statements]&.reset
209
+ adapter.send(:async_configure)
210
+ end
211
+ true
212
+ end
213
+
214
+ #: (RawEntry entry) -> bool
215
+ def clean?(entry)
216
+ raw = entry.raw
217
+ !raw.finished? && raw.status == PG::CONNECTION_OK && raw.transaction_status == PG::PQTRANS_IDLE
218
+ end
219
+
220
+ #: (untyped raw) -> void
221
+ def close(raw)
222
+ raw.close unless raw.finished?
223
+ end
224
+
225
+ #: (untyped raw) -> bool
226
+ def healthy?(raw)
227
+ return false if raw.finished? || raw.status != PG::CONNECTION_OK
228
+
229
+ raw.query(';')
230
+ true
231
+ rescue PG::Error
232
+ false
233
+ end
234
+
235
+ # Points the socket at /dev/null, as `PostgreSQLAdapter#discard!` does, so freeing the connection in the
236
+ # child cannot end the parent's session.
237
+ #
238
+ #: (untyped raw) -> void
239
+ def discard(raw)
240
+ raw.socket_io.reopen(IO::NULL)
241
+ rescue StandardError
242
+ nil
243
+ end
244
+
245
+ #: (untyped raw) -> bool
246
+ def in_flight?(raw)
247
+ !raw.finished? && raw.transaction_status == PG::PQTRANS_ACTIVE
248
+ end
249
+
250
+ private
251
+
252
+ # Records what the adapter's `configure_connection` set up, if it ran on this raw connection, and routes its
253
+ # notices to whichever adapter is attached.
254
+ #
255
+ #: (untyped adapter, RawEntry entry) -> void
256
+ def take_configuration(adapter, entry)
257
+ configuration = adapter.instance_variable_get(:@async_pg_configured)
258
+ return unless configuration && configuration[:raw].equal?(entry.raw)
259
+
260
+ adapter.instance_variable_set(:@async_pg_configured, nil)
261
+ state = entry.state
262
+ state[:defaults] = configuration[:settings]
263
+ state[:role] = configuration[:role]
264
+ state[:settings] = configuration[:settings].dup
265
+ state[:mapped_default_timezone] = configuration[:mapped_default_timezone]
266
+ state[:timestamp_decoder] = configuration[:timestamp_decoder]
267
+ state[:type_map_for_results] = configuration[:type_map_for_results]
268
+ route_notices(entry)
269
+ end
270
+
271
+ #: (RawEntry entry) -> void
272
+ def route_notices(entry)
273
+ entry.raw.set_notice_receiver { |result| self.class.route_notice(entry.owner, result) }
274
+ end
275
+
276
+ # Statements prepared under an older generation may be stale (see `RawPool#statement_generation`), so they
277
+ # are deallocated on this raw connection first.
278
+ #
279
+ #: (untyped adapter, RawEntry entry) -> void
280
+ def adopt_statements(adapter, entry)
281
+ state = entry.state
282
+ statements = state[:statements] ||= adapter.send(:build_statement_pool)
283
+ statements.instance_variable_set(:@connection, adapter)
284
+ adapter.instance_variable_set(:@statements, statements)
285
+
286
+ generation = adapter.async_raw_pool.statement_generation
287
+ statements.clear if state.key?(:generation) && state[:generation] != generation
288
+ state[:generation] = generation
289
+ end
290
+
291
+ #: (untyped adapter, RawEntry entry) -> void
292
+ def reconcile(adapter, entry)
293
+ settings = entry.state[:settings]
294
+ desired(adapter, entry).each do |key, value|
295
+ next if settings.fetch(key, UNKNOWN) == value
296
+
297
+ apply(adapter, entry, key, value, materialize_transactions: false)
298
+ settings[key] = value
299
+ end
300
+ end
301
+
302
+ # The adapter's values, or the configured ones where the adapter has none.
303
+ #
304
+ #: (untyped adapter, RawEntry entry) -> Hash[Symbol, untyped]
305
+ def desired(adapter, entry)
306
+ defaults = entry.state[:defaults]
307
+ {
308
+ session_auth: adapter.instance_variable_get(:@async_pg_session_auth) || defaults[:session_auth],
309
+ search_path: adapter.instance_variable_get(:@schema_search_path) || defaults[:search_path],
310
+ client_min_messages: adapter.instance_variable_get(:@async_pg_min_messages) ||
311
+ defaults[:client_min_messages],
312
+ }
313
+ end
314
+
315
+ # Values come from the adapter's setters, as ActiveRecord interpolates them, or from `SHOW` for the configured
316
+ # session user, which is quoted. Restoring the configured session user restores the configured role too.
317
+ #
318
+ #: (untyped adapter, RawEntry entry, Symbol key, untyped value, materialize_transactions: bool) -> void
319
+ def apply(adapter, entry, key, value, materialize_transactions:)
320
+ case key
321
+ when :search_path then statements = ["SET search_path TO #{value}"]
322
+ when :client_min_messages then statements = ["SET client_min_messages TO '#{value}'"]
323
+ else statements = session_auth_statements(adapter, entry, value)
324
+ end
325
+ statements.each { |sql| adapter.send(:internal_execute, sql, 'SCHEMA', materialize_transactions:) }
326
+ end
327
+
328
+ #: (untyped adapter, RawEntry entry, String? user) -> Array[String]
329
+ def session_auth_statements(adapter, entry, user)
330
+ defaults = entry.state[:defaults] || {}
331
+ return ["SET SESSION AUTHORIZATION #{user || 'DEFAULT'}"] unless user == defaults[:session_auth]
332
+
333
+ role = entry.state[:role]
334
+ ["SET SESSION AUTHORIZATION #{user ? adapter.quote(user) : 'DEFAULT'}",
335
+ *("SET SESSION role TO #{adapter.quote(role)}" if role),]
336
+ end
337
+ end
338
+ end
339
+
340
+ Handler.register('ActiveRecord::ConnectionAdapters::PostgreSQLAdapter', Handlers::PostgreSQL,
341
+ load_hook: :active_record_postgresqladapter,
342
+ excludes: ['ActiveRecord::ConnectionAdapters::CockroachDBAdapter'])
343
+ end
344
+ end
345
+
346
+ require 'active_record/async_connection_pool/handlers/postgresql/adapter_methods'
347
+ require 'active_record/async_connection_pool/handlers/postgresql/pg_query_detector'
@@ -0,0 +1,143 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ module ActiveRecord
5
+ module AsyncConnectionPool
6
+ module Handlers
7
+ class SQLite3 < Handler
8
+ # Prepended to `SQLite3Adapter` after `AdapterExtension`. With a raw pool, the raw connection stays attached
9
+ # for as long as the adapter uses it, `disable_referential_integrity` pins, and a `read_uncommitted`
10
+ # transaction restores the setting on its own raw connection before detaching. Without one, every method
11
+ # defers to ActiveRecord.
12
+ module AdapterMethods
13
+ # ActiveRecord reads the encoding from `any_raw_connection`, which would detach before reading it.
14
+ #
15
+ #: () -> String
16
+ def encoding
17
+ return super unless async_raw_pool
18
+
19
+ with_raw_connection(materialize_transactions: false) { |raw| raw.encoding.to_s }
20
+ end
21
+
22
+ # Pinned for its block, since `PRAGMA foreign_keys` is set outside a transaction. ActiveRecord sets and
23
+ # restores the pragmas itself, so they are not detected; the block's own statements are. If the pragmas may
24
+ # not have been restored, the raw connection is tainted.
25
+ #
26
+ #: [T] () { () -> T } -> T
27
+ def disable_referential_integrity(&block)
28
+ return super unless async_raw_pool
29
+
30
+ detection = @async_detection_disabled
31
+ failures = [] #: Array[Exception]
32
+ pin do
33
+ without_session_state_detection do
34
+ super() { async_sqlite_referential_block(detection, failures, &block) }
35
+ end
36
+ rescue Exception => error # rubocop:disable Lint/RescueException
37
+ @async_entry&.taint! unless failures.any? { |failure| failure.equal?(error) }
38
+ raise
39
+ end
40
+ end
41
+
42
+ #: () -> untyped
43
+ def commit_db_transaction
44
+ return super unless async_raw_pool
45
+
46
+ async_sqlite_ending_transaction(transaction_over: false) { super }
47
+ end
48
+
49
+ #: () -> untyped
50
+ def rollback_db_transaction
51
+ return super unless async_raw_pool
52
+
53
+ async_sqlite_ending_transaction(transaction_over: true) { super }
54
+ end
55
+
56
+ # Clears the attached raw connection's statements, as ActiveRecord does, and bumps the raw pool's statement
57
+ # generation so every other raw connection, idle or attached elsewhere, clears its own before its next
58
+ # attach. A detached adapter has no statements of its own to clear.
59
+ #
60
+ #: (?new_connection: bool) -> void
61
+ def clear_cache!(new_connection: false)
62
+ super
63
+ return if new_connection || !(raw_pool = async_raw_pool)
64
+
65
+ generation = raw_pool.bump_statement_generation!
66
+ @async_entry&.state&.store(:generation, generation)
67
+ end
68
+
69
+ # Restored by `commit_db_transaction` or `rollback_db_transaction` instead, while still attached.
70
+ #
71
+ #: () -> void
72
+ def reset_isolation_level
73
+ super unless async_raw_pool
74
+ end
75
+
76
+ private
77
+
78
+ # Runs the block of `disable_referential_integrity` with detection as it was outside, and records what it
79
+ # raises: any other error means the pragmas may not have been restored.
80
+ #
81
+ #: [T] (bool detection, Array[Exception] failures) { () -> T } -> T
82
+ def async_sqlite_referential_block(detection, failures)
83
+ inner = @async_detection_disabled
84
+ @async_detection_disabled = detection
85
+ yield
86
+ rescue Exception => error # rubocop:disable Lint/RescueException
87
+ failures << error
88
+ raise
89
+ ensure
90
+ @async_detection_disabled = inner
91
+ end
92
+
93
+ # Keeps the value to restore with the raw connection rather than the adapter, which may detach first.
94
+ # `PRAGMA read_uncommitted=ON` is part of the transaction, so it is not session state.
95
+ #
96
+ #: (untyped mode, untyped isolation) -> void
97
+ def internal_begin_transaction(mode, isolation)
98
+ return super unless async_raw_pool && isolation
99
+
100
+ without_session_state_detection { super }
101
+ @async_entry&.state&.store(:previous_read_uncommitted, @previous_read_uncommitted)
102
+ @previous_read_uncommitted = nil
103
+ end
104
+
105
+ # Restores `read_uncommitted` once `COMMIT` or `ROLLBACK` succeeds, before the raw connection detaches.
106
+ #
107
+ #: [T] (transaction_over: bool) { () -> T } -> T
108
+ def async_sqlite_ending_transaction(transaction_over:)
109
+ @async_depth += 1
110
+ begin
111
+ result = yield
112
+ async_sqlite_restore_read_uncommitted
113
+ result
114
+ ensure
115
+ @async_depth -= 1
116
+ async_detach_if_idle(transaction_over:)
117
+ end
118
+ end
119
+
120
+ # The transaction is over, so a failure must not look like one of `COMMIT`: the setting stays recorded,
121
+ # and the handler taints the raw connection on release.
122
+ #
123
+ #: () -> void
124
+ def async_sqlite_restore_read_uncommitted
125
+ return unless (entry = @async_entry) && entry.state.key?(:previous_read_uncommitted)
126
+
127
+ previous = entry.state[:previous_read_uncommitted]
128
+ without_session_state_detection do
129
+ internal_execute("PRAGMA read_uncommitted=#{previous}", 'TRANSACTION', materialize_transactions: false)
130
+ end
131
+ entry.state.delete(:previous_read_uncommitted)
132
+ rescue StandardError
133
+ nil
134
+ end
135
+ end
136
+ end
137
+ end
138
+ end
139
+ end
140
+
141
+ ActiveSupport.on_load(:active_record_sqlite3adapter) do
142
+ prepend ActiveRecord::AsyncConnectionPool::Handlers::SQLite3::AdapterMethods
143
+ end
@@ -0,0 +1,183 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ require 'uri'
5
+
6
+ module ActiveRecord
7
+ module AsyncConnectionPool
8
+ module Handlers
9
+ # SQLite runs in-process, so a query blocks the thread; pooling still frees idle fibers' connections. State kept
10
+ # per raw connection in `RawEntry#state`:
11
+ #
12
+ # - `:statements`: the raw connection's statement pool.
13
+ # - `:previous_read_uncommitted`: the `read_uncommitted` setting to restore when the `read_uncommitted`
14
+ # transaction open on the raw connection ends.
15
+ class SQLite3 < Handler
16
+ # Every pattern below needs one of these words, so most statements skip lexing.
17
+ HINT = /pragma|attach|detach|temp|load_extension/i
18
+
19
+ # A schema or pragma name. Quoted names are blanked to `''` in the code view.
20
+ NAME = %q{(?:[\p{Alnum}_]+|'')}
21
+
22
+ # Pragmas that take an argument without changing the session: they list, check or act on the database.
23
+ ARGUMENT_PRAGMAS = %w[
24
+ table_info table_xinfo table_list index_info index_xinfo index_list foreign_key_list foreign_key_check
25
+ integrity_check quick_check wal_checkpoint incremental_vacuum optimize
26
+ ].freeze
27
+
28
+ # `PRAGMA name` and `PRAGMA name(table)` read; `PRAGMA name = value` and `PRAGMA name(value)` set. A temp
29
+ # object lives in the connection's `temp` schema, as does what `ATTACH` and `load_extension` add.
30
+ SESSION_STATE_CODE_PATTERNS = [
31
+ /\APRAGMA\s+(?:#{NAME}\s*\.\s*)?#{NAME}\s*=/o,
32
+ /\APRAGMA\s+(?:#{NAME}\s*\.\s*)?(?!(?:#{ARGUMENT_PRAGMAS.join('|')})\s*\()#{NAME}\s*\(/o,
33
+ /\AATTACH\b/,
34
+ /\ADETACH\b/,
35
+ /\ACREATE\s+TEMP(?:ORARY)?\b/,
36
+ /\ACREATE\s+(?:UNIQUE\s+|VIRTUAL\s+)?(?:TABLE|VIEW|TRIGGER|INDEX)\s+
37
+ (?:IF\s+NOT\s+EXISTS\s+)?(?:temp|'')\s*\./x,
38
+ /\bload_extension\s*\(/,
39
+ ].freeze
40
+
41
+ # Whether the database is in memory and private to each connection, as the adapter decides for `:memory:`,
42
+ # extended to `file:` URIs: `file::memory:` or `mode=memory`, unless `cache=shared`.
43
+ #
44
+ #: (String database) -> bool
45
+ def self.memory_database?(database)
46
+ return true if database == ':memory:'
47
+ return false unless database.start_with?('file:')
48
+
49
+ path, query = database.delete_prefix('file:').split('?', 2)
50
+ params = URI.decode_www_form(query.to_s).to_h
51
+ (path == ':memory:' || params['mode'] == 'memory') && params['cache'] != 'shared'
52
+ end
53
+
54
+ # Each connection to a private in-memory database sees its own database, so there is only one.
55
+ #
56
+ #: (Integer requested) -> Integer
57
+ def max_raw_connections(requested)
58
+ private_memory_database? ? 1 : requested
59
+ end
60
+
61
+ # Closing the only raw connection to a private in-memory database would delete the database, so it is kept
62
+ # even when its session state is unknown. Every fiber shares that one connection by design anyway.
63
+ #
64
+ #: () -> bool
65
+ def private_memory_database?
66
+ return @private_memory_database if defined?(@private_memory_database)
67
+
68
+ @private_memory_database = self.class.memory_database?(db_config.database.to_s)
69
+ end
70
+
71
+ # Prepared statements belong to the raw connection they were prepared on, so the adapter uses that
72
+ # connection's statement pool while attached. Statements cached under an older statement generation (see
73
+ # `RawPool#statement_generation`) are finalized first: the driver keeps the columns a statement was prepared
74
+ # with, so after a schema change they would read rows with the old columns.
75
+ #
76
+ #: (untyped adapter, RawEntry entry) -> void
77
+ def adopt(adapter, entry)
78
+ state = entry.state
79
+ statements = state[:statements] ||= adapter.send(:build_statement_pool)
80
+ adapter.instance_variable_set(:@statements, statements)
81
+
82
+ generation = adapter.async_raw_pool.statement_generation
83
+ statements.clear if state.key?(:generation) && state[:generation] != generation
84
+ state[:generation] = generation
85
+ end
86
+
87
+ #: () -> Symbol
88
+ def sql_dialect
89
+ :sqlite
90
+ end
91
+
92
+ #: () -> Array[Regexp | String]
93
+ def session_state_code_patterns
94
+ SESSION_STATE_CODE_PATTERNS
95
+ end
96
+
97
+ #: (String sql) -> bool
98
+ def session_state_statement?(sql)
99
+ sql.match?(HINT) && super
100
+ end
101
+
102
+ # A `read_uncommitted` setting not restored leaves the raw connection in an unknown state. A transaction left
103
+ # open on a private in-memory database is rolled back, since that raw connection is kept regardless.
104
+ #
105
+ #: (untyped adapter, RawEntry entry) -> void
106
+ def release(adapter, entry)
107
+ entry.taint! if entry.state.key?(:previous_read_uncommitted)
108
+ adapter.instance_variable_set(:@statements, nil)
109
+ raw = entry.raw
110
+ return unless private_memory_database? && !raw.closed? && raw.transaction_active?
111
+
112
+ begin
113
+ raw.rollback
114
+ rescue StandardError
115
+ nil
116
+ end
117
+ end
118
+
119
+ # SQLite has no way to clear a connection's session (pragmas, temp schema, attached databases), so a tainted
120
+ # raw connection is closed. On a private in-memory database it is kept instead, with a warning, once per raw
121
+ # connection, that its session state carries over.
122
+ #
123
+ #: (untyped adapter, RawEntry entry) -> bool
124
+ def reset(adapter, entry) # rubocop:disable Naming/PredicateMethod
125
+ return false unless private_memory_database?
126
+
127
+ unless entry.state[:session_state_warned]
128
+ entry.state[:session_state_warned] = true
129
+ (adapter&.logger || ActiveRecord::Base.logger)&.warn(
130
+ "Session state on the in-memory SQLite database #{db_config.database.inspect} cannot be reset, so it " \
131
+ 'carries over to whichever fiber uses the database next.'
132
+ )
133
+ end
134
+ true
135
+ end
136
+
137
+ # A raw connection still in a transaction after `release` tried to roll it back is broken, so it is closed
138
+ # even on a private in-memory database: the next fiber would see its uncommitted writes.
139
+ #
140
+ #: (RawEntry entry) -> bool
141
+ def clean?(entry)
142
+ !entry.raw.closed? && !entry.raw.transaction_active?
143
+ end
144
+
145
+ # The raw connection to a private in-memory database holds the database, so idle and age limits never close
146
+ # it. Health checks still do.
147
+ #
148
+ #: (RawEntry _entry) -> bool
149
+ def expirable?(_entry)
150
+ !private_memory_database?
151
+ end
152
+
153
+ #: (untyped raw) -> void
154
+ def close(raw)
155
+ raw.close unless raw.closed?
156
+ end
157
+
158
+ # SQLite defers closing a connection until its statements are finalized, and until then the connection keeps
159
+ # any open transaction and its lock on the database, so the cached statements are finalized first.
160
+ #
161
+ #: (RawEntry entry) -> void
162
+ def close_entry(entry)
163
+ entry.state.delete(:statements)&.clear unless entry.raw.closed?
164
+ ensure
165
+ super
166
+ end
167
+
168
+ #: (untyped raw) -> bool
169
+ def healthy?(raw)
170
+ return false if raw.closed?
171
+
172
+ raw.execute('SELECT 1')
173
+ true
174
+ end
175
+ end
176
+ end
177
+
178
+ Handler.register('ActiveRecord::ConnectionAdapters::SQLite3Adapter', Handlers::SQLite3,
179
+ load_hook: :active_record_sqlite3adapter)
180
+ end
181
+ end
182
+
183
+ require 'active_record/async_connection_pool/handlers/sqlite3/adapter_methods'