You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
1.1 KiB

  1. -- This file was automatically created by Diesel to setup helper functions
  2. -- and other internal bookkeeping. This file is safe to edit, any future
  3. -- changes will be added to existing projects as new migrations.
  4. -- Sets up a trigger for the given table to automatically set a column called
  5. -- `updated_at` whenever the row is modified (unless `updated_at` was included
  6. -- in the modified columns)
  7. --
  8. -- # Example
  9. --
  10. -- ```sql
  11. -- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW());
  12. --
  13. -- SELECT diesel_manage_updated_at('users');
  14. -- ```
  15. CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$
  16. BEGIN
  17. EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s
  18. FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl);
  19. END;
  20. $$ LANGUAGE plpgsql;
  21. CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$
  22. BEGIN
  23. IF (
  24. NEW IS DISTINCT FROM OLD AND
  25. NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at
  26. ) THEN
  27. NEW.updated_at := current_timestamp;
  28. END IF;
  29. RETURN NEW;
  30. END;
  31. $$ LANGUAGE plpgsql;