Vistas Materializadas Postgresql
Introducción a PostgreSQL
Álvaro Herrera
1er Foro Mundial de Tecnolog’ia Libre
Álvaro Herrera
Introducción a PostgreSQL
Vistas Materializadas
La Situación deEjemplo
Una compañía de teléfonos tiene una tabla con todas las llamadas telefónicas efectuadas por sus clientes, y desea tener una tabla con los totales de llamadas.
Álvaro HerreraIntroducción a PostgreSQL
Vistas Materializadas
Ejemplo: La Tabla de Llamadas
Tabla «public.llamadas» Columna cliente_id inicio fin Tipo integer timestamp with time zone timestamp with time zoneModificadores not null REFERENCES clientes not null not null
Álvaro Herrera
Introducción a PostgreSQL
Vistas Materializadas
Ejemplo: La Vista Materializada
Tabla «public.total_llamadas»Columna cliente_id anno mes duracion_total Tipo integer integer integer interval Modificadores not null REFERENCES clientes not null not null not null
Álvaro Herrera
Introducción a PostgreSQLVistas Materializadas
Ejemplo: El Trigger de Inserción
CREATE OR REPLACE FUNCTION agrega_al_total() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN LOOP UPDATE total_llamadas SET duracion_total =duracion_total + (NEW.fin - NEW.inicio) WHERE cliente_id = NEW.cliente_id AND anno = extract(year FROM NEW.inicio) AND mes = extract(month FROM NEW.inicio); IF FOUND THEN RETURN; END IF;
Álvaro HerreraIntroducción a PostgreSQL
Vistas Materializadas
Ejemplo: El Trigger de Inserción (cont.)
BEGIN INSERT INTO total_llamadas (cliente_id, anno, mes, duracion_total) VALUES (NEW.cliente_id,extract(year FROM NEW.inicio), extract(month FROM NEW.inicio), NEW.fin - NEW.inicio); EXCEPTION WHEN unique_violation THEN -- no hacer nada END; END LOOP; END;
Álvaro Herrera Introducción a PostgreSQLVistas Materializadas
Demo
INSERT INTO llamadas (cliente_id, inicio, fin) VALUES (1, ’2005-10-21 10:00’, ’2005-10-21 10:45’); SELECT * FROM total_llamadas; cliente_id 1 (1 fila) anno 2005 mes...
Regístrate para leer el documento completo.