From a93d24501c3fc3358617000eca1b286a98a03a7f Mon Sep 17 00:00:00 2001 From: Arpit Jalan Date: Thu, 4 Jun 2020 11:26:40 +0530 Subject: [PATCH] FIX: base import script was not updating first_post_created_at column FEATURE: new rake task to update first_post_created_at column The not-equal operator (`<>`) in PostgreSQL does not compare values with NULL. We should instead use `IS DISTINCT FROM` when comparing values with NULL. --- lib/tasks/import.rake | 19 +++++++++++++++++++ script/import_scripts/base.rb | 4 ++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/lib/tasks/import.rake b/lib/tasks/import.rake index 9084a6492a6..12d97adc4a6 100644 --- a/lib/tasks/import.rake +++ b/lib/tasks/import.rake @@ -497,3 +497,22 @@ task 'import:file', [:file_name] => [:environment] do |_, args| ImportExport.import(args[:file_name]) puts "", "Done", "" end + +desc "Update first_post_created_at column in user_stats table" +task "import:update_first_post_created_at" => :environment do + puts "", "Updating first_post_created_at..." + + DB.exec <<~SQL + WITH sub AS ( + SELECT user_id, MIN(posts.created_at) AS first_post_created_at + FROM posts + GROUP BY user_id + ) + UPDATE user_stats + SET first_post_created_at = sub.first_post_created_at + FROM user_stats u1 + JOIN sub ON sub.user_id = u1.user_id + WHERE u1.user_id = user_stats.user_id + AND user_stats.first_post_created_at IS DISTINCT FROM sub.first_post_created_at + SQL +end diff --git a/script/import_scripts/base.rb b/script/import_scripts/base.rb index 035c8a3e572..a42b8c3dda9 100644 --- a/script/import_scripts/base.rb +++ b/script/import_scripts/base.rb @@ -684,7 +684,7 @@ class ImportScripts::Base FROM users u1 JOIN lpa ON lpa.user_id = u1.id WHERE u1.id = users.id - AND users.last_posted_at <> lpa.last_posted_at + AND users.last_posted_at IS DISTINCT FROM lpa.last_posted_at SQL end @@ -702,7 +702,7 @@ class ImportScripts::Base FROM user_stats u1 JOIN sub ON sub.user_id = u1.user_id WHERE u1.user_id = user_stats.user_id - AND user_stats.first_post_created_at <> sub.first_post_created_at + AND user_stats.first_post_created_at IS DISTINCT FROM sub.first_post_created_at SQL puts "", "Updating user post_count..."