Created
June 28, 2015 19:37
-
-
Save kungfuant/7e6c7f9b0ef7eb18c4ed to your computer and use it in GitHub Desktop.
Initialize incremental leaderboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const START_GAME_ID = 1580000; | |
const co = require('co'); | |
const wait = require('co-wait'); | |
const pg = require('pg'); | |
const cpg = require('co-pg')(pg); | |
let databaseUrl = process.env.DATABASE_URL; | |
if (!databaseUrl) | |
throw new Error('must set DATABASE_URL environment var'); | |
pg.types.setTypeParser(20, function(val) { // parse int8 as an integer | |
return val === null ? null : parseInt(val); | |
}); | |
function *query(sql, params) { | |
let vals = yield cpg.connectPromise(process.env.DATABASE_URL); | |
let client = vals[0]; | |
let done = vals[1]; | |
try { | |
return yield client.queryPromise(sql, params); | |
} finally { | |
done(); | |
} | |
} | |
function* processUser(userId) { | |
let sql, par, result; | |
sql = | |
'SELECT ' + | |
' (COALESCE(sum(cash_out - bet), 0::numeric) + COALESCE(sum(bonus), 0::numeric))::bigint AS gross_profit, ' + | |
' (COALESCE(sum(cash_out), 0::numeric) + COALESCE(sum(bonus), 0::numeric) - COALESCE(sum(bet), 0::numeric))::bigint AS net_profit, ' + | |
' COUNT(*) AS games_played ' + | |
' FROM plays WHERE game_id < $1 AND user_id = $2'; | |
par = [START_GAME_ID, userId]; | |
result = yield* query(sql, par); | |
console.assert(result.rows.length === 1); | |
result = result.rows[0]; | |
sql = | |
'UPDATE users ' + | |
' SET ' + | |
' gross_profit = gross_profit + $1, ' + | |
' net_profit = net_profit + $2, ' + | |
' games_played = games_played + $3 ' + | |
' WHERE id = $4'; | |
par = [result.gross_profit, result.net_profit, result.games_played, userId]; | |
yield* query(sql, par); | |
} | |
function* getUsers() { | |
let result = yield* query('SELECT id FROM users', []); | |
return result.rows.map(row => row.id); | |
} | |
co(function*(){ | |
let users = yield* getUsers(); | |
for(let k = 0; k < users.length; ++k) { | |
if (k % 100 == 0) | |
console.log('Processed', k + '/' + users.length); | |
yield* processUser(users[k]); | |
yield wait(100); | |
} | |
pg.end(); | |
}).catch(function(err) { | |
console.error('Something went wrong.'); | |
console.error(err.stack); | |
throw err; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment