Files
mostlymatter/db/migrations/postgres/000076_upgrade_lastrootpostat.up.sql
Kyriakos Z 501d454af5 MM-39351: fixes LastRootPostAt being null (#19574)
* MM-39351: fixes LastRootPostAt being null

After upgrading to v6.1 there is a chance for LastRootPostAt to be NULL.
This might be due to a faulty migration when upgrading to v5.35.

v5.35 had `create_msg_root_count` where LastRootPostAt was used as a
temporary column which at the end was deleted.
Then on v6.1 we are adding that column again, this time to keep.

If the migration to v5.35 had failed and it didn't drop the column
the `upgrade_cte` (v6.1) migration would leave some channels with `LastRootPostAt`
being NULL.

This resulted in crashing the app.

This commit fixes that by running again a migration to again set
LastRootPostAt only when it's NULL this time and then set it to 0
for channels that might still have LastRootPostAt being NULL
(channels with no posts).

PS: the whole issue arose when upon creating the `upgrade_cte` migration
the create_msg_root_count migration was manually edited to change
the column name from LastRootPostAt to LastRootAt.

Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
2022-02-22 12:13:04 +02:00

51 строка
1.0 KiB
SQL

DO $$
BEGIN
IF (
SELECT count(*)
FROM information_schema.columns
WHERE table_schema='public'
AND table_name='channels'
AND column_name='lastrootpostat'
AND (column_default IS NULL OR column_default != '''0''::bigint')
) = 1 THEN
ALTER TABLE channels ALTER COLUMN lastrootpostat SET DEFAULT '0'::bigint;
END IF;
END$$;
DO $$
BEGIN
IF (
SELECT count(*)
FROM Channels
WHERE LastRootPostAt IS NULL
) > 0 THEN
-- fixes migrate cte and sets the LastRootPostAt for channels that don't have it set
WITH q AS (
SELECT
Channels.Id channelid,
COALESCE(MAX(Posts.CreateAt), 0) AS lastrootpost
FROM
Channels
LEFT JOIN
Posts
ON
Channels.Id = Posts.ChannelId
WHERE
Posts.RootId = ''
GROUP BY
Channels.Id
)
UPDATE
Channels
SET
LastRootPostAt = q.lastrootpost
FROM
q
WHERE
q.channelid = Channels.Id AND Channels.LastRootPostAt IS NULL;
-- sets LastRootPostAt to 0, for channels with no posts
UPDATE Channels SET LastRootPostAt=0 WHERE LastRootPostAt IS NULL;
END IF;
END $$;