Skip to content

Commit

Permalink
Update campaign_contact.updated_at on change
Browse files Browse the repository at this point in the history
  • Loading branch information
sjwmoveon committed May 3, 2024
1 parent 816fd7d commit ddcd444
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
32 changes: 32 additions & 0 deletions migrations/20240503180901_campaigncontactsupdatedat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@

/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/

const { onUpdateTrigger } = require('./helpers/index')
const ON_UPDATE_TIMESTAMP_FUNCTION = `
CREATE OR REPLACE FUNCTION on_update_timestamp()
RETURNS trigger AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ language 'plpgsql';
`

const DROP_ON_UPDATE_TIMESTAMP_FUNCTION = `DROP FUNCTION on_update_timestamp`

exports.up = async function(knex) {
await knex.raw(ON_UPDATE_TIMESTAMP_FUNCTION);
await knex.raw(onUpdateTrigger('campaign_contact'));
};

/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.down = async function(knex) {
await knex.raw("DROP TRIGGER campaign_contact_updated_at on campaign_contact");
await knex.raw(DROP_ON_UPDATE_TIMESTAMP_FUNCTION);
};
8 changes: 8 additions & 0 deletions migrations/helpers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,11 @@ exports.redefineSqliteTable = async (knex, tableName, newTableFn) => {
await knex.schema.dropTable(tableName);
await knex.schema.createTable(tableName, newTableFn);
};


exports.onUpdateTrigger = table => `
CREATE TRIGGER ${table}_updated_at
BEFORE UPDATE ON ${table}
FOR EACH ROW
EXECUTE PROCEDURE on_update_timestamp();
`

0 comments on commit ddcd444

Please sign in to comment.