diff --git a/scripts/generate_user_space_counters.ts b/scripts/generate_user_space_counters.ts new file mode 100644 index 00000000..8e06d112 --- /dev/null +++ b/scripts/generate_user_space_counters.ts @@ -0,0 +1,31 @@ +import 'dotenv/config'; +import db from '../src/helpers/mysql'; + +// Usage: yarn ts-node scripts/generate_user_space_counters.ts +async function main() { + console.log('Inserting/Updating proposals_count'); + const proposalsCountRes = await db.queryAsync( + `INSERT INTO user_space (proposals_count, user_id, space_id) + (select * from (select count(id) as proposals_count, author, space from proposals group by author, space) as t) + ON DUPLICATE KEY UPDATE proposals_count = t.proposals_count` + ); + console.log(proposalsCountRes); + + console.log('Inserting/Updating votes_count'); + const votesCountRes = await db.queryAsync( + `INSERT INTO user_space (votes_count, user_id, space_id) + (select * from (select count(id) as votes_count, voter, space from votes group by voter, space) as t) + ON DUPLICATE KEY UPDATE votes_count = t.votes_count` + ); + console.log(votesCountRes); +} + +(async () => { + try { + await main(); + process.exit(0); + } catch (e) { + console.error(e); + process.exit(1); + } +})(); diff --git a/src/helpers/schema.sql b/src/helpers/schema.sql index eea3849a..a4c69274 100644 --- a/src/helpers/schema.sql +++ b/src/helpers/schema.sql @@ -142,3 +142,14 @@ CREATE TABLE statements ( INDEX created (created), INDEX updated (updated) ); + +CREATE TABLE user_space ( + user_id varchar(64) NOT NULL, + space_id varchar(64) NOT NULL, + votes_count smallint unsigned NOT NULL DEFAULT '0', + proposals_count smallint unsigned NOT NULL DEFAULT '0', + UNIQUE KEY user_id_space_id (user_id,space_id), + INDEX space_id (space_id), + INDEX votes_count (votes_count), + INDEX proposals_count (proposals_count) +);