Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
syuilo opened this issue Mar 24, 2022 · 9 comments
Labels
packages/backend Server side specific issue/PR 🐢Performance Efficiency related issue/PR 💚Refactor Rewriting code without changing behavior

Comments

@syuilo
Copy link
Member

syuilo commented Mar 24, 2022

Summary

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

@syuilo syuilo added packages/backend Server side specific issue/PR 💚Refactor Rewriting code without changing behavior labels Mar 24, 2022
@syuilo syuilo self-assigned this Mar 24, 2022
@codeninja
Copy link

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.

@syuilo
Copy link
Member Author

syuilo commented Jun 28, 2022

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

@syuilo syuilo changed the title count系のカラムはトリガーで更新するようにしたい count系、updatedAt系のカラムはトリガーで更新するようにしたい Jul 10, 2022
@syuilo
Copy link
Member Author

syuilo commented Jul 10, 2022

こんな感じか

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();

ローカルで動作確認

@rinsuki
Copy link
Contributor

rinsuki commented Jul 10, 2022

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

@syuilo
Copy link
Member Author

syuilo commented Jul 10, 2022

もちろんdelete分も作る

@syuilo
Copy link
Member Author

syuilo commented Jul 11, 2022

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

@sao-coding
Copy link

sao-coding commented May 22, 2024

すみませんが
この問題はまだ注目されていますか?

@syuilo
Copy link
Member Author

syuilo commented May 22, 2024

PR募集しています

@syuilo
Copy link
Member Author

syuilo commented Sep 16, 2024

そもそもキューイングしてバルク的に更新した方が良さそう

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
packages/backend Server side specific issue/PR 🐢Performance Efficiency related issue/PR 💚Refactor Rewriting code without changing behavior
Projects
Development

No branches or pull requests

4 participants