misskey icon indicating copy to clipboard operation
misskey copied to clipboard

count系、updatedAt系のカラムはトリガーで更新するようにしたい

Open syuilo opened this issue 2 years ago • 6 comments

Summary

アプリケーションサイドでやるとCASCADE削除とかに対応できないし処理的にも無駄なため ただTypeORMでは現在migrationに直接SQL書く以外でトリガーの定義はサポートされていない https://github.com/typeorm/typeorm/issues/1082

syuilo avatar Mar 24 '22 11:03 syuilo

Translation for those who find this :)

If you do it on the application side, you can not deal with CASCADE deletion and it is useless in terms of processing However, TypeORM does not currently support the definition of triggers other than writing SQL directly in migration.

codeninja avatar Apr 28 '22 15:04 codeninja

しょうがないから生SQL書くかしら

syuilo avatar Jun 28 '22 00:06 syuilo

こんな感じか

CREATE FUNCTION user_update_notes_count() RETURNS trigger AS $body$
BEGIN
  IF (TG_OP = 'INSERT') THEN
    UPDATE "user" SET "notesCount" = "notesCount" + 1 WHERE "user"."id" = NEW."userId";
    RETURN NEW;
  ELSE
    UPDATE "user" SET "notesCount" = "notesCount" - 1 WHERE "user"."id" = OLD."userId";
    RETURN OLD;
  END IF;
END;
$body$
LANGUAGE plpgsql;
CREATE TRIGGER user_update_notes_count_trigger AFTER INSERT OR DELETE ON "note" FOR EACH ROW
EXECUTE FUNCTION user_update_notes_count();

ローカルで動作確認

syuilo avatar Jul 10 '22 13:07 syuilo

それだと結局CASCADE削除とかに対応できてなくない?

rinsuki avatar Jul 10 '22 14:07 rinsuki

もちろんdelete分も作る

syuilo avatar Jul 10 '22 14:07 syuilo

あーCASCADEでdeleteされるレコードはトリガ発火しないとかそういうこと?

syuilo avatar Jul 11 '22 04:07 syuilo