From 9593a30c3cdfa976a2b690d939b5155f463e11a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janko=20Marohni=C4=87?= Date: Mon, 10 Nov 2025 21:50:27 +0100 Subject: [PATCH] Close any database connections at the end of each request There is no need to reuse database connections for the LSP server, as the overhead of establishing new connections locally is negligible. Therefore, we can close any active database connections as soon as we're done with the request. --- lib/ruby_lsp/ruby_lsp_rails/server.rb | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/lib/ruby_lsp/ruby_lsp_rails/server.rb b/lib/ruby_lsp/ruby_lsp_rails/server.rb index 1fc3b9f4..9daa56a8 100644 --- a/lib/ruby_lsp/ruby_lsp_rails/server.rb +++ b/lib/ruby_lsp/ruby_lsp_rails/server.rb @@ -294,6 +294,7 @@ def start request = JSON.parse(json, symbolize_names: true) execute(request.fetch(:method), request[:params]) + disconnect_from_database end end @@ -493,6 +494,18 @@ def clear_file_system_resolver_hooks end end + # Keeping a connection to the database prevents it from being dropped in development. We don't actually need to + # to reuse database connections for the LSP server, the performance benefit of doing so only matters in production + # where there is latency, locally we're fine with the small overhead of establishing a new connection on each request. + #: -> void + def disconnect_from_database + return unless defined?(::ActiveRecord::Base) + + with_notification_error_handling("disconnect_from_database") do + ActiveRecord::Base.connection_handler.clear_all_connections!(:all) + end + end + #: (singleton(ActiveRecord::Base)) -> Array[String] def collect_model_foreign_keys(model) return [] unless model.connection.respond_to?(:supports_foreign_keys?) &&