From 1dc6fdcd6696f42760d0d8ee36758530b1874636 Mon Sep 17 00:00:00 2001 From: Fabien O'Carroll Date: Thu, 4 Feb 2021 12:41:30 +0000 Subject: [PATCH] Added customQuery to handle subscribed aggregates refs https://github.com/TryGhost/Ghost/issues/12602 In order to build up a list of un/subscribes over time we have to use the customQuery functionality to run SQL aggregates - this is "hidden" behind an option, so that we can find{All,Page} as usual. --- core/server/models/member-subscribe-event.js | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/core/server/models/member-subscribe-event.js b/core/server/models/member-subscribe-event.js index 7f5b534a84..4946a0fc10 100644 --- a/core/server/models/member-subscribe-event.js +++ b/core/server/models/member-subscribe-event.js @@ -1,6 +1,22 @@ +const errors = require('@tryghost/errors'); const ghostBookshelf = require('./base'); -const MemberSubscribeEvent = ghostBookshelf.Model.extend({tableName: 'members_subscribe_events'}, { +const MemberSubscribeEvent = ghostBookshelf.Model.extend({ + tableName: 'members_subscribe_events', + customQuery(qb, options) { + if (options.aggregateSubscriptionDeltas) { + if (options.limit || options.filter) { + throw new errors.IncorrectUsageError('aggregateSubscriptionDeltas does not work when passed a filter or limit'); + } + const knex = ghostBookshelf.knex; + return qb.clear('select') + .select(knex.raw(`DATE(created_at) as date`)) + .select(knex.raw(`SUM(CASE WHEN subscribed THEN 1 ELSE -1 END) as subscribed_delta`)) + .groupByRaw(`DATE(created_at)`) + .orderByRaw(`DATE(created_at)`); + } + } +}, { async edit() { throw new errors.IncorrectUsageError('Cannot edit MemberSubscribeEvent'); },