Outdated version of the documentation. Find the latest one here.

16.6. Lesson: Reglas

Las reglas permiten la “un árbol de consulta” de una consulta de entrada para reescribir. Un uso común es implementar vistas, incluyendo vista actualizable .*- Wikipedia*

La meta de esta lección: Aprender cómo crear nuevas reglas para la base de datos.

16.6.1. Materialised Views (Rule based views)

Say you want to log every change of phone_no in your people table in to a people_log table. So you set up a new table:

create table people_log (name text, time timestamp default NOW());

In the next step, create a rule that logs every change of a phone_no in the people table into the people_log table:

create rule people_log as on update to people
  where NEW.phone_no <> OLD.phone_no
  do insert into people_log values (OLD.name);

To test that the rule works, let’s modify a phone number:

update people set phone_no = '082 555 1234' where id = 2;

Check that the people table was updated correctly:

select * from people where id=2;

 id |    name    | house_no | street_id |   phone_no
----+------------+----------+-----------+--------------
  2 | Joe Bloggs |        3 |         2 | 082 555 1234
(1 row)

Now, thanks to the rule we created, the people_log table will look like this:

select * from people_log;

    name    |            time
------------+----------------------------
 Joe Bloggs | 2014-01-11 14:15:11.953141
(1 row)

Nota

El valor del campo time dependerá de la fecha y hora actual.

16.6.2. In Conclusion

Reglas le permiten agregar automáticamente o cambiar los datos de su base de datos para reflejar los cambios en otras partes de la base de datos.

16.6.3. What’s Next?

El siguiente módulo le dará a conocer las base de datos espaciales utilizando PostGIS, que toma estos conceptos de bases de datos y las aplica a los datos GIS.