Files
ArtSplash/scripts/create_artwork_vote_counts_view.js
2026-02-22 10:18:15 +05:30

43 lines
1.1 KiB
JavaScript

const { Pool } = require('pg');
require('dotenv').config();
const createViewQuery = `
CREATE OR REPLACE VIEW artwork_vote_counts AS
SELECT
a.id AS artwork_id,
a.title,
a.category,
a.image_url,
p.participant_name,
p.department,
p.year,
COUNT(v.id) AS vote_count
FROM artworks a
JOIN participants p ON a.participant_id = p.id
LEFT JOIN votes v ON a.id = v.artwork_id
GROUP BY a.id, a.title, a.category, a.image_url, p.participant_name, p.department, p.year
ORDER BY vote_count DESC;
`;
async function createView() {
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
try {
console.log('Connecting to the database...');
const client = await pool.connect();
console.log('Creating or replacing artwork_vote_counts view...');
await client.query(createViewQuery);
console.log('artwork_vote_counts view created or replaced successfully.');
client.release();
} catch (error) {
console.error('Error creating artwork_vote_counts view:', error);
} finally {
await pool.end();
}
}
createView();