PostgreSQLで更新日時を記録する「update_at」カラムを実現させる
データベースを作っていく上で、最低限必要とされているカラムに
id
、created_at
、updated_at
があります。
MySQLの場合は、
DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
とカラムに設定することで、更新時に日時も合わせて更新されるという仕様になっていますが、PostgreSQLにはありません。
そこで、PostgreSQLではトリガーと、トリガーで実行される関数をを仕込んでやっていく様になるみたいで…凄いですね。
create table tests ( id integer primary key, name text not null, created_at timestamp not null default current_timestamp, updated_at timestamp not null default current_timestamp );
create function set_update_time() returns opaque as ' begin new.updated_at := ''now''; return new; end; ' language 'plpgsql';
create trigger update_tri before update on posts for each row execute procedure set_update_time();
これを順に実行すればOKでした。