Skip to content

Commit

Permalink
Merge pull request #13 from MoveOnOrg/updatedat
Browse files Browse the repository at this point in the history
Update campaign_contact.updated_at on change
  • Loading branch information
sjwmoveon authored May 3, 2024
2 parents 816fd7d + 454e1db commit de74eb9
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
35 changes: 35 additions & 0 deletions migrations/20240503180901_campaigncontactsupdatedat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

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`

/**
* @param { import("knex").Knex } knex
*/
exports.up = async function(knex) {
const isSqlite = /sqlite/.test(knex.client.config.client);
if (!isSqlite) {
await knex.raw(ON_UPDATE_TIMESTAMP_FUNCTION);
await knex.raw(onUpdateTrigger('campaign_contact'));
}
};

/**
* @param { import("knex").Knex } knex
*/
exports.down = async function(knex) {
const isSqlite = /sqlite/.test(knex.client.config.client);
if (!isSqlite) {
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 de74eb9

Please sign in to comment.