What is the recommended way to abstract out common code when writing the database schema?
I've multiple tables that have created_at and updated_at columns.
create table if not exists profiles
(
...
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
...
create index on profiles (created_at);
create index on profiles (updated_at);
create trigger handle_updated_at
before update
on profiles
for each row
execute procedure moddatetime(updated_at);
Repeating this code for each table has the following drawbacks
- pain to write
- difficult to refactor (say you have to change
created_attocreated) - the real intent of the code gets buried due to too much boilerplate
Other usecases
- automatically adding an index to all foreign key constraints
- automatically creating mapping tables to represent relation b/w two entities
Solutions I'm aware of
- use an ORM - most ORMs allow you to write abstract classes that don't map to any database table, but can be inherited by child classes that do map to tables.
- write a function that takes in a table name and alters the table to add the desired columns, triggers and indices
I don't particularly like this because I'm being forced to encode the query as a string.create or replace function add_created_at(table_name varchar(63)) returns void language plpgsql security invoker as $$ begin execute format('alter table %I add column created_at timestamptz not null;', table_name); end; $$;
Is there a better way?