Skip to content

Conversation

@denispeplin
Copy link

This is not a "real" pull request, I don't expect it will be merged. It is just what I do to use this gem with Rails (I'm importing data from other application, which sends data without timestamps).
I tried other way: using now() as default for timestamp columns in database, but only INSERT can benefit from this approach, and UPDATE leaves updated_at untouched.

@evadne
Copy link
Contributor

evadne commented Jan 21, 2016

Hello @denispeplin

My solution to this is to use triggers instead of making Upsert depend on having timestamp columns. Some tables I use Upsert on do not have timestamp columns. You can create a couple trigger functions like these.

CREATE OR REPLACE FUNCTION public.bump_created_at()
RETURNS TRIGGER AS $$
BEGIN
  NEW.created_at = coalesce(NEW.created_at, now());
  NEW.updated_at = coalesce(NEW.updated_at, now());
  RETURN NEW;
END;
$$ language 'plpgsql';

CREATE OR REPLACE FUNCTION public.bump_updated_at()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = coalesce(NEW.updated_at, now());
  RETURN NEW;   
END;
$$ language 'plpgsql';

Then for something like an objects table…

CREATE TRIGGER objects_updated_at
  BEFORE UPDATE ON objects
  FOR EACH ROW EXECUTE PROCEDURE
  bump_updated_at();

CREATE TRIGGER objects_created_at
  BEFORE INSERT ON objects
  FOR EACH ROW EXECUTE PROCEDURE
  bump_created_at();

Note that in Postgres, now() gives you time at start of transaction and statement_timestamp() gives you time at start of statement, so you may want to adjust accordingly.

urimikhli added a commit to urimikhli/upsert that referenced this pull request Apr 14, 2016
urimikhli added a commit to urimikhli/upsert that referenced this pull request Apr 14, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants