Importante

A tradução é um esforço comunitário você pode contribuir. Esta página está atualmente traduzida em 40.00%.

15.6. Lesson: Rules

As regras permitem a “árvore de comando” de uma consulta de entrada para ser reescrito. Um uso comum é a implementação de pontos de vista, incluindo visão atualizável. - Wikipedia

O objetivo dessa lição: Aprender a criar novas regras para o banco de dados.

15.6.1. Criando uma regra de log

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

Para testar se a regra funciona, vamos modificar um número de telefone:

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

The value of the time field will depend on the current date and time.

15.6.2. In Conclusion

As regras permitem que você automaticamente adicione ou altere dados em seu banco de dados para refletir mudanças em outras partes do banco de dados.

15.6.3. What’s Next?

The next module will introduce you to Spatial Database using PostgreSQL with PostGIS extension, which takes these database concepts and applies them to GIS data.