blog.anqou.net
rss
author
tags

NixOS で stateVersion を保ったまま新しい PostgreSQL を使う

自分がメインで使っている NixOS の環境は NixOS 24.05 の時にセットアップしたものなので configuration.nixstateVersion には "24.05" が設定されています:

{
  # This value determines the NixOS release from which the default
  # settings for stateful data, like file locations and database versions
  # on your system were taken. It‘s perfectly fine and recommended to leave
  # this value at the release version of the first install of this system.
  # Before changing this value read the documentation for this option
  # (e.g. man configuration.nix or on https://nixos.org/nixos/options.html).
  system.stateVersion = "24.05"; # Did you read the comment?
}

生成されたコメントにもあるように、この値は PostgreSQL などのマイグレーションが単純ではないソフトウェアのバージョンを決める際に用いられます。そのため NixOS のインストール後は値を変えずに運用することが想定されているようで、実際自分も変えずに使ってきました。

ところで最近 NixOS 26.05 にアップデートしたタイミングから psql コマンドを打つと以下のような警告が出るようになりました:

$ psql postgres
WARNING:  database "postgres" has a collation version mismatch
DETAIL:  The database was created using collation version 2.40, but the operating system provides version 2.42.
HINT:  Rebuild all objects in this database that use the default collation and run ALTER DATABASE postgres REFRESH COLLATION VERSION, or build PostgreSQL with the right library version.
psql (17.10, server 15.18)
Type "help" for help.

postgres=>

これは要するに PostgreSQL のバージョンがクライアントに比べて古すぎるということだと理解したので、手元の PostgreSQL を更新することにしました。これは単に services.postgresql.package を変更することで行えます:

{
  services.postgresql = {
    enable = true;
    package = pkgs.postgresql_18; # PostgreSQL 18 を使う
  };
}

NixOS は自動でマイグレーションを走らせてはくれないので、このようにして立ち上がった PostgreSQL 18 は空っぽです。これが困る場合は pg_upgrade を利用して移行する必要がありますが、手元の PostgreSQL は主に開発用に一時的に作る DB が主で、データが失われても大した問題ではなかったのでそのまま使うことにしました。いつも anqou ロールで操作を行うので、以下のコマンドでこれだけ作成しました:

$ psql -U postgres postgres
psql (18.4)
Type "help" for help.

postgres=# create role anqou with superuser login ;
CREATE ROLE
postgres=#
\q