Skip to content

Commit

Permalink
The touch trigger should update the timestamp column when it is curre…
Browse files Browse the repository at this point in the history
…ntly NULL
  • Loading branch information
magnetised committed Feb 13, 2014
1 parent c1e575e commit 6d3fe93
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/sequel_postgresql_triggers.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -126,11 +126,11 @@ def pgt_touch(main_table, touch_table, column, expr, opts={})
sql = <<-SQL sql = <<-SQL
BEGIN BEGIN
IF (TG_OP = 'INSERT') THEN IF (TG_OP = 'INSERT') THEN
UPDATE #{quote_schema_table(touch_table)} SET #{quote_identifier(column)} = CURRENT_TIMESTAMP WHERE #{cond['NEW']} AND #{quote_identifier(column)} <> CURRENT_TIMESTAMP; UPDATE #{quote_schema_table(touch_table)} SET #{quote_identifier(column)} = CURRENT_TIMESTAMP WHERE #{cond['NEW']} AND ((#{quote_identifier(column)} <> CURRENT_TIMESTAMP) OR (#{quote_identifier(column)} IS NULL));
ELSIF (TG_OP = 'UPDATE') THEN ELSIF (TG_OP = 'UPDATE') THEN
UPDATE #{quote_schema_table(touch_table)} SET #{quote_identifier(column)} = CURRENT_TIMESTAMP WHERE #{cond['NEW']} AND #{quote_identifier(column)} <> CURRENT_TIMESTAMP; UPDATE #{quote_schema_table(touch_table)} SET #{quote_identifier(column)} = CURRENT_TIMESTAMP WHERE #{cond['NEW']} AND ((#{quote_identifier(column)} <> CURRENT_TIMESTAMP) OR (#{quote_identifier(column)} IS NULL));
ELSIF (TG_OP = 'DELETE') THEN ELSIF (TG_OP = 'DELETE') THEN
UPDATE #{quote_schema_table(touch_table)} SET #{quote_identifier(column)} = CURRENT_TIMESTAMP WHERE #{cond['OLD']} AND #{quote_identifier(column)} <> CURRENT_TIMESTAMP; UPDATE #{quote_schema_table(touch_table)} SET #{quote_identifier(column)} = CURRENT_TIMESTAMP WHERE #{cond['OLD']} AND ((#{quote_identifier(column)} <> CURRENT_TIMESTAMP) OR (#{quote_identifier(column)} IS NULL));
END IF; END IF;
RETURN NULL; RETURN NULL;
END; END;
Expand Down
9 changes: 9 additions & 0 deletions spec/sequel_postgresql_triggers_spec.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -220,5 +220,14 @@
DB[:children].delete DB[:children].delete
DB[:parents].get(:changed_on).should > time DB[:parents].get(:changed_on).should > time
end end

specify "Should update the timestamp on the related table if that timestamp is initially NULL" do
DB.pgt_touch(:children, :parents, :changed_on, :id1=>:parent_id1)
DB[:parents] << {:id1=>1, :changed_on=>nil}
DB[:children] << {:id=>1, :parent_id1=>1}
changed_on = DB[:parents].get(:changed_on)
changed_on.should_not == nil
changed_on.strftime('%F').should == Date.today.strftime('%F')
end
end end
end end

0 comments on commit 6d3fe93

Please sign in to comment.