Não sou especialista em DBMS e estou tentando construir um sistema de alerta que possa se anexar a muitas tabelas , então imaginei que fazer a pergunta ajudaria minha arquitetura.
O que pode me confundir um pouco é que você pode ter vários alertas anexados a cada modelo (sessões, eventos, organização) que estão representados em tabelas do meu banco de dados. Um registro de cada modelo pode ter vários alertas diferentes sendo emitidos.
A maneira mais simples de resolver isso é criar uma tabela como
CREATE TABLE alerts (
id uuid DEFAULT uuid_generate_v4() PRIMARY KEY,
alert_type character varying(50) NOT NULL,
metadata jsonb,
session_id uuid REFERENCES sessions(id) ON DELETE DO NOTHING ON UPDATE CASCADE,
event_id uuid REFERENCES events(id) ON DELETE DO NOTHING ON UPDATE CASCADE,
organization_id uuid REFERENCES organizations(id) ON DELETE DO NOTHING ON UPDATE CASCADE,
created_at timestamp without time zone,
updated_at timestamp without time zone
);
Mas parece ser uma má estratégia aumentarmos isso para muito mais tabelas anexadas ao sistema de alerta. Obviamente não escala bem. Estou hesitando entre duas estratégias.
Você tem uma tabela alerts
e representa uma many-to-many
segunda tabela alerts_relations
que possui table_name
e table_id
dá sentido a cada outro modelo/tabela ao qual está anexado.
CREATE TABLE alerts (
id uuid DEFAULT uuid_generate_v4() PRIMARY KEY,
alert_type character varying(50) NOT NULL,
metadata jsonb,
created_at timestamp without time zone,
updated_at timestamp without time zone
);
CREATE TABLE alerts_relations (
id uuid DEFAULT uuid_generate_v4() PRIMARY KEY,
alert_id uuid REFERENCES alerts(id) ON DELETE CASCADE ON UPDATE CASCADE,
table_name character varying(50) NOT NULL,
table_id character varying(50) NOT NULL,
created_at timestamp without time zone,
updated_at timestamp without time zone
);
A outra estratégia remove table_name
e table_id
substitui-a pela seguinte
CREATE TABLE session_alerts (
session_id uuid REFERENCES sessions(id) ON DELETE CASCADE ON UPDATE CASCADE
) INHERITS (alert_relations);
CREATE TABLE event_alerts (
event_id uuid REFERENCES events(id) ON DELETE CASCADE ON UPDATE CASCADE
) INHERITS (alert_relations);
CREATE TABLE organization_alerts (
organization_id uuid REFERENCES organizations(id) ON DELETE CASCADE ON UPDATE CASCADE
) INHERITS (alert_relations);
Estou me perguntando qual estratégia produz melhor desempenho e qual é a mais fácil de manter. Se isso ajudar, minha base de código está em Golang, então tenho que trabalhar manualmente no SQL e fazer pouco trabalho de ORM.
A última estratégia parece ser a mais conveniente para minha lógica de negócios porque cada relacionamento pode ser representado com uma tabela e um nome diferentes. Parece mais fácil de manter, mas não tenho certeza de nada neste momento; pode haver desvantagens que não vejo.
Qualquer outra solução é bem-vinda, claro! Obrigado por ler.