DEV Community

cesarcastmore
cesarcastmore

Posted on

2 2

Modularización de trigger de PSQL: parte 1

Los triggers por tabla tienden a crecer en numero: conforme la aplicacion crece, surgen nuevos requerimientos y cambian lógicas de negocio. En algun momento la tabla tiene tantos trigger que algunos desarrolladores los separan por prefijos o por algun id.

Si en la aplicacion conviven un numero de empresas, cada entidad de la base de datos puede tener diferentes lógicas de negocios. Los desarrolladores recurren a crear diferentes triggers por empresa. Si un trigger tiene una lógica que es única en un negocio, el control es mediante el id del negocio. Este control se vuelve mas complicado cuando ciertos negocios tienen la misma lógica y recurrimos a modificar el trigger para agregar la nueva empresa.

Una manera para mejorar el control de lógicas de negocio es modularizarlo mediante una tabla.


CREATE TABLE public.ad_module
(
    id serial,
    updated_at timestamp without time zone DEFAULT now(),
    created_at timestamp without time zone DEFAULT now(),
    name character varying(255) COLLATE pg_catalog."default",
    version numeric,
    CONSTRAINT module_pkey PRIMARY KEY (id)
)
WITH (
    OIDS = FALSE
)

Esta tabla es muy básica, solo tiene un nombre y la version. Un modulo puede tener muchos negocios, por lo tanto ocupamos una segunda tabla para tener una relación de una a muchos.



CREATE TABLE public.ad_business_module
(
    id serial,
    business_id integer,
    ad_module_id integer,
    updated_at timestamp without time zone DEFAULT now(),
    created_at timestamp without time zone DEFAULT now(),
    CONSTRAINT ad_business_module_pkey PRIMARY KEY (id),
    CONSTRAINT ad_business_module_bus_fk FOREIGN KEY (business_id)
        REFERENCES public.businesses (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT ad_business_module_module_fk FOREIGN KEY (ad_module_id)
        REFERENCES public.ad_module (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
)
WITH (
    OIDS = FALSE
)

La tabla ad_business_module tendrá n registro de empresas en el cual convivirán el misma lógica de negocio. Podemos crear el modulo Venta y en la tabla ad_business_module indicara que empresas comparten esa misma lógica de negocio.

Si en la base de datos conviven un numero de empresas, es sumamente importante conocer a quien pertenece cada registro, es indispensable colocar un business_id a cada tabla de la base de datos.


ALTER TABLE public.invoice
    ADD COLUMN business_id integer;

Cuando se cree, actualice o elimine un registro en cualquier tabla de la base de datos, por medio business_id conoceremos a quien pertenece ese registro.

El mi siguiente blog hablare como modularizar los triggers usando la informacion de las tablas anteriores y como usar los esquemas de base de datos para agregar trigger modulo y esquema.

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 🕒

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay