Unverified Commit c0c664b3 authored by Diogo Correia's avatar Diogo Correia
Browse files

nixos/immich: reindex VectorChord indexes on update

VectorChord requires its indexes to be reindexed when the extension is
updated. [1]
This commit adds functionality to save the current version of the
extension before performing an update, and then compare it with the
updated version to decide whether it should reindex Immich's indexes.
This complexity is needed to avoid reindexing every time PostgreSQL is
started, as it is an expensive operation that would slow down startup.

[1]: https://docs.immich.app/administration/postgres-standalone/#updating-vectorchord
parent 385f0a2e
Loading
Loading
Loading
Loading
+15 −0
Original line number Diff line number Diff line
@@ -323,7 +323,11 @@ in
          "vchord"
        ];
        sqlFile = pkgs.writeText "immich-pgvectors-setup.sql" (
          # save previous version of vectorchord to trigger reindex on update
          lib.optionalString cfg.database.enableVectorChord ''
            SELECT COALESCE(installed_version, ''') AS vchord_version_before FROM pg_available_extensions WHERE name = 'vchord' \gset
          ''
          + ''
            ${lib.concatMapStringsSep "\n" (ext: "CREATE EXTENSION IF NOT EXISTS \"${ext}\";") extensions}
            ${lib.concatMapStringsSep "\n" (ext: "ALTER EXTENSION \"${ext}\" UPDATE;") extensions}
            ALTER SCHEMA public OWNER TO ${cfg.database.user};
@@ -332,6 +336,17 @@ in
            ALTER SCHEMA vectors OWNER TO ${cfg.database.user};
            GRANT SELECT ON TABLE pg_vector_index_stat TO ${cfg.database.user};
          ''
          # trigger reindex if vectorchord updates
          # https://docs.immich.app/administration/postgres-standalone/#updating-vectorchord
          + lib.optionalString cfg.database.enableVectorChord ''
            SELECT COALESCE(installed_version, ''') AS vchord_version_after FROM pg_available_extensions WHERE name = 'vchord' \gset

            SELECT (:'vchord_version_before' != ''' AND :'vchord_version_before' != :'vchord_version_after') AS has_vchord_updated \gset
            \if :has_vchord_updated
              REINDEX INDEX face_index;
              REINDEX INDEX clip_index;
            \endif
          ''
        );
      in
      [