Files
once-campfire/lib/tasks/room_messages_count.rake
T
Cursor Agent 1f5858098b Keep bot page totals on SQLite-maintained rooms.messages_count
X-Total-Count on GET /rooms/:id/:bot_key/messages was COUNT(*) of the
room on every page. Serve it from rooms.messages_count updated by SQLite
triggers so Rails, bulk SQL, and foreign writers stay in step — without
ActiveRecord counter_cache callbacks those paths skip.

Fixes #309.

Co-authored-by: Thomas Klemm <github@tklemm.eu>
2026-10-07 19:36:01 +00:00

39 lines
1.1 KiB
Ruby

# schema.rb cannot dump SQLite triggers. Reinstall after loads, and re-append
# Room::MessagesCount.install! after dumps so the call is not lost.
namespace :room_messages_count do
task ensure: :environment do
ActiveRecord::Base.connection_pool.with_connection do |connection|
next unless connection.adapter_name.match?(/sqlite/i)
Room::MessagesCount.ensure!(connection)
end
end
task append_schema_install: :environment do
schema = Rails.root.join("db/schema.rb")
contents = schema.read
marker = "Room::MessagesCount.install!"
next if contents.include?(marker)
contents.sub!(/\nend\n?\z/, <<~RUBY)
# SQLite triggers are not dumped by schema.rb; keep rooms.messages_count honest after schema:load.
#{marker}
end
RUBY
schema.write(contents)
end
end
{
"db:schema:load" => "room_messages_count:ensure",
"db:test:load_schema" => "room_messages_count:ensure",
"db:schema:dump" => "room_messages_count:append_schema_install"
}.each do |task_name, enhancement|
next unless Rake::Task.task_defined?(task_name)
Rake::Task[task_name].enhance do
Rake::Task[enhancement].invoke
end
end