ALTER TABLE posts
  ADD COLUMN IF NOT EXISTS author_id UUID REFERENCES users(id) ON DELETE SET NULL;

UPDATE posts
SET author_id = (
  SELECT id
  FROM (
    SELECT id
    FROM users
    WHERE user_role IN ('owner', 'admin')
      OR is_admin = true
  ) privileged_users
  LIMIT 1
)
WHERE author_id IS NULL
  AND (
    SELECT COUNT(*)
    FROM users
    WHERE user_role IN ('owner', 'admin')
      OR is_admin = true
  ) = 1;

CREATE INDEX IF NOT EXISTS posts_author_id_idx
  ON posts (author_id);
