diff --git a/migrations/20181026220312-first-types-materialized-view.js b/migrations/20181026220312-first-types-materialized-view.js new file mode 100644 index 0000000..7a2d062 --- /dev/null +++ b/migrations/20181026220312-first-types-materialized-view.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = { + up: (queryInterface, Sequelize) => { + return queryInterface.sequelize.query('CREATE MATERIALIZED VIEW first_type AS SELECT DISTINCT(type), MIN("createdAt") FROM events GROUP BY type'); + }, + + down: (queryInterface, Sequelize) => { + return queryInterface.sequelize.query('DROP MATERIALIZED VIEW first_type'); + } +}; diff --git a/src/models/index.ts b/src/models/index.ts index 7a36786..67c5e17 100644 --- a/src/models/index.ts +++ b/src/models/index.ts @@ -35,4 +35,15 @@ Object.keys(db).forEach(modelName => { db.sequelize = sequelize; db.Sequelize = Sequelize; + +/* + * Periodically refresh the materialized view for holding the first types + */ +setInterval(() => { + logger.info('Refreshing the `first_type` materialized view'); + sequelize.query('REFRESH MATERIALIZED VIEW first_type'); +}, ((60 * 1000) * 60)); + + + export default db;