const pg = require('pg'); class Database { static instance; constructor(connectionStr) { this.pool = new pg.Pool({connectionString: connectionStr}); Database.instance = this; } async prepareUser(id) { let client = await this.pool.connect(); let user = null; try { await client.query('BEGIN'); let res = await client.query('SELECT * FROM santa_users WHERE id = $1', [id]); if (res.rowCount === 0) { await client.query('INSERT INTO santa_users (id) VALUES ($1)', [id]); res = await client.query('SELECT * FROM santa_users WHERE id = $1', [id]); } await client.query('COMMIT'); user = res.rows[0]; } finally { client.release(); } return user; } async setGameState(id, state) { let client = await this.pool.connect(); try { await client.query('BEGIN'); await client.query('UPDATE santa_users SET ingame = $1 WHERE id = $2', [state, id]); await client.query('COMMIT'); } finally { client.release(); } } async enterGame(id, first_name, last_name, group, problems) { let client = await this.pool.connect(); try { await client.query('BEGIN'); await client.query('UPDATE santa_users SET first_name = $1, last_name = $2, group_name = $3, problems = $4, ingame = true WHERE id = $5', [first_name, last_name, group, problems, id]); await client.query('COMMIT'); } finally { client.release(); } } async getUsersCount() { let client = await this.pool.connect(); let count = null; try { await client.query('BEGIN'); let res = await client.query('SELECT COUNT(*) as count FROM santa_users WHERE ingame = true'); await client.query('COMMIT'); count = res.rows[0].count; } finally { client.release(); } return count; } } module.exports = Database;