const pg = require('pg'); class Database { constructor(connectionStr) { this.pool = new pg.Pool({connectionString: connectionStr}); } async registerQRTeam(name, owner) { let client = await this.pool.connect(); try { await client.query('BEGIN'); await client.query('INSERT INTO qr_team (team_name, owner_id) values ($1,$2)', [name, owner]); await client.query('COMMIT'); } finally { client.release(); } } /** * * @param code * @returns {Promise} */ async getQRTask(code) { let client = await this.pool.connect(); let task = null; try { await client.query('BEGIN'); let res = await client.query('SELECT * FROM qr_tasks WHERE code = $1', [code]); await client.query('COMMIT'); task = res.rows[0]; } finally { client.release(); } return task; } async getTask(id) { if(id === 0) return {short_name: "Начало"} let client = await this.pool.connect(); let task = null; try { await client.query('BEGIN'); let res = await client.query('SELECT * FROM qr_tasks WHERE id = $1', [id]); await client.query('COMMIT'); task = res.rows[0]; } finally { client.release(); } return task; } async getTop() { let client = await this.pool.connect(); let teams = []; try { await client.query('BEGIN'); let res = await client.query('SELECT qr_team.*, COUNT(task) as count\n' + 'FROM qr_team\n' + ' join qr_completion as com on qr_team.id = com.group_id\n' + 'group by id, team_name, owner_id\n' + 'ORDER BY count DESC', []); await client.query('COMMIT'); teams = res.rows; } finally { client.release(); } return teams; } /** * * @param team * @param task * @returns {Promise} */ async checkPreviousTasks(team, task) { if(task === 1) return true; let client = await this.pool.connect(); let prevtasks = 0; try { await client.query('BEGIN'); let res = await client.query('SELECT * FROM qr_view WHERE task < $1 AND group_id = $2', [task, team]); prevtasks = res.rowCount; await client.query('COMMIT'); } finally { client.release(); } return prevtasks === task - 1; } async getTeam(user) { let client = await this.pool.connect(); let team = null; try { await client.query('BEGIN'); let res = await client.query('SELECT * FROM qr_team WHERE owner_id = $1', [user]); await client.query('COMMIT'); team = res.rows[0]; } finally { client.release(); } return team; } async addCompletion(team, task) { let client = await this.pool.connect(); try { await client.query('BEGIN'); await client.query('INSERT INTO qr_completion (group_id, task) values ($1,$2)', [team, task]); await client.query('COMMIT'); } finally { client.release(); } } async addView(team, task) { let client = await this.pool.connect(); try { await client.query('BEGIN'); await client.query('INSERT INTO qr_view (group_id, task) values ($1,$2)', [team, task]); await client.query('COMMIT'); } finally { client.release(); } } } module.exports = Database;