Skip to content
51 changes: 51 additions & 0 deletions Week2/assignment/Ex2Relationships.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Client } from "pg";

// Database connection configuration
const config = {
host: "localhost",
user: "hyfuser",
password: "hyfpassword",
database: "DBassignmentW2",
port: 5432,
};

const client = new Client(config);

async function createTables(client) {
const CREATE_RESEARCH_PAPERS_TABLE = `
CREATE TABLE IF NOT EXISTS research_papers (
paper_id SERIAL PRIMARY KEY,
paper_title VARCHAR(50) NOT NULL,
conference VARCHAR(50),
publish_date DATE
)`;

const CREATE_PAPER_AUTHORS_TABLE = `
CREATE TABLE IF NOT EXISTS paper_authors (
paper_id INTEGER NOT NULL,
author_id INTEGER NOT NULL,
PRIMARY KEY (paper_id, author_id),
CONSTRAINT fk_paper
FOREIGN KEY (paper_id)
REFERENCES research_papers(paper_id)
ON DELETE CASCADE,
CONSTRAINT fk_author
FOREIGN KEY (author_id)
REFERENCES authors(author_id)
ON DELETE CASCADE
)`;

try {
await client.connect();
console.log("Connected to PostgreSQL database!");

// Create tables
await client.query(CREATE_RESEARCH_PAPERS_TABLE);
await client.query(CREATE_PAPER_AUTHORS_TABLE);
} catch (error) {
console.error("Error creating tables:", error);
} finally {
await client.end();
}
}
createTables(client);
162 changes: 162 additions & 0 deletions Week2/assignment/Ex3AddInfo&Joins.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { Client } from "pg";
import { authors, researchPapers, paperAuthors } from "./generateSampleData.js";

// Database connection configuration
const config = {
host: "localhost",
user: "hyfuser",
password: "hyfpassword",
database: "DBassignmentW2",
port: 5432,
};

const client = new Client(config);
let queryRes;

async function insertAuthors(client) {
try {
// Insert authors with mentors
for (let i = 0; i < authors.length; i++) {
const author = authors[i];
// Set mentor to null for the first 5 authors (they will be mentors)
// Others will have a random mentor from the first 5 authors
const mentorId = i < 5 ? null : Math.floor(Math.random() * 5) + 1;

const query = {
text: `
INSERT INTO authors (author_name, university, date_of_birth, h_index, gender, mentor)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING author_id
`,
values: [
author.name,
author.university,
author.dob,
author.hIndex,
author.gender,
mentorId,
],
};

const result = await client.query(query);
console.log(
`Inserted author: ${author.name} with ID: ${result.rows[0].author_id}`
);
}
console.log("All authors inserted successfully");
} catch (error) {
console.error("Error inserting authors:", error);
throw error;
}
}

async function insertResearchPapers(client) {
try {
for (const paper of researchPapers) {
const query = {
text: `
INSERT INTO research_papers (paper_title, conference, publish_date)
VALUES ($1, $2, $3)
RETURNING paper_id
`,
values: [paper.title, paper.conference, paper.date],
};

const result = await client.query(query);
console.log(
`Inserted paper: ${paper.title} with ID: ${result.rows[0].paper_id}`
);
}
console.log("All research papers inserted successfully");
} catch (error) {
console.error("Error inserting research papers:", error);
throw error;
}
}

async function insertPaperAuthors(client) {
try {
for (const paperAuthor of paperAuthors) {
const query = {
text: `
INSERT INTO paper_authors (paper_id, author_id)
VALUES ($1, $2)
ON CONFLICT DO NOTHING
`,
values: [paperAuthor.paper_id, paperAuthor.authorId],
};

await client.query(query);
console.log(
`Linked paper ${paperAuthor.paper_id} with author ${paperAuthor.authorId}`
);
}
console.log("All paper-author relationships inserted successfully");
} catch (error) {
console.error("Error inserting paper-author relationships:", error);
throw error;
}
}

async function seedDatabase(client) {
try {
await client.connect();
console.log("Connected to PostgreSQL database!");

// Insert new data
await insertAuthors(client);
await insertResearchPapers(client);
await insertPaperAuthors(client);

// Create a view for all authors and their corresponding mentors
const CREATE_AUTHOR_MENTOR_VIEW = `
CREATE OR REPLACE VIEW author_mentor AS
SELECT
author_name,
mentor
FROM
authors
`;

await client.query(CREATE_AUTHOR_MENTOR_VIEW);
// Query the view to verify it works
queryRes = await client.query("SELECT * FROM author_mentor");
console.log(
"\nAuthors with their mentors:",
JSON.stringify(queryRes.rows, null, 2)
);

// Create a view for all the vegetarian recipes with potatoes
const CREATE_AUTHORS_PAPERS_VIEW = `
CREATE OR REPLACE VIEW authors_papers AS
SELECT
a.author_name,
rp.paper_title
FROM
authors a
LEFT JOIN paper_authors pa ON a.author_id = pa.author_id
LEFT JOIN research_papers rp ON pa.paper_id = rp.paper_id
`;

await client.query(CREATE_AUTHORS_PAPERS_VIEW);
// Query the view to verify it works
queryRes = await client.query("SELECT * FROM authors_papers");
if (queryRes.rows.length !== 0) {
console.log(
"\nAuthors with their papers:",
JSON.stringify(queryRes.rows, null, 2)
);
} else {
console.log("There are no papers in the database");
}

console.log("Database seeding completed successfully!");
} catch (error) {
console.error("Error seeding database:", error);
} finally {
await client.end();
}
}

// Execute the seeding function
seedDatabase(client);
140 changes: 140 additions & 0 deletions Week2/assignment/Ex4AggregateFunctions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import { Client } from "pg";
import { authors, researchPapers, paperAuthors } from "./generateSampleData.js";

// Database connection configuration
const config = {
host: "localhost",
user: "hyfuser",
password: "hyfpassword",
database: "DBassignmentW2",
port: 5432,
};

const client = new Client(config);
let queryRes;

async function createDBviews(client) {
try {
await client.connect();
console.log("Connected to PostgreSQL database!");

// Create a view for all research papers and the number of authors that wrote that paper.
const CREATE_AUTHOR_QUANTITY_VIEW = `
CREATE OR REPLACE VIEW paper_authors_qty AS
SELECT
paper_title,
COUNT(pa.author_id) as number_of_authors
FROM
research_papers rp
JOIN paper_authors pa ON rp.paper_id = pa.paper_id
GROUP BY paper_title
`;

await client.query(CREATE_AUTHOR_QUANTITY_VIEW);

queryRes = await client.query("SELECT * FROM paper_authors_qty");
console.log(
"\nResearch papers and the number of their authors:",
JSON.stringify(queryRes.rows, null, 2)
);

// Create a view for the sum of the research papers published by all female authors.
const CREATE_FEMALE_PAPER_NUMBER_VIEW = `
CREATE OR REPLACE VIEW female_paper_number AS
SELECT
COUNT(DISTINCT rp.paper_id) as publications_sum
FROM
research_papers rp
JOIN paper_authors pa ON rp.paper_id = pa.paper_id
JOIN authors a ON a.author_id = pa.author_id
WHERE a.gender = 'Female'
`;

await client.query(CREATE_FEMALE_PAPER_NUMBER_VIEW);

queryRes = await client.query("SELECT * FROM female_paper_number");
console.log(
"\nThe sum of the research papers published by all female authors:",
JSON.stringify(queryRes.rows, null, 2)
);

// Create a view for Average of the h-index of all authors per university.
const CREATE_HINDEX_VIEW = `
CREATE OR REPLACE VIEW h_index AS
SELECT
university,
AVG(h_index) as average_h_index
FROM authors
GROUP BY university
`;

await client.query(CREATE_HINDEX_VIEW);
queryRes = await client.query("SELECT * FROM h_index");
console.log(
"\nThe average of the h-index of all authors per university:",
JSON.stringify(queryRes.rows, null, 2)
);

// Create a view for the sum of the research papers per university.
const CREATE_PAPERS_PER_UNIVERSITY_VIEW = `
CREATE OR REPLACE VIEW papers_per_university AS
SELECT
a.university,
COUNT(DISTINCT rp.paper_id) as university_publications
FROM authors a
JOIN paper_authors pa ON pa.author_id = a.author_id
JOIN research_papers rp ON rp.paper_id = pa.paper_id
GROUP BY a.university
`;

await client.query(CREATE_PAPERS_PER_UNIVERSITY_VIEW);
queryRes = await client.query("SELECT * FROM papers_per_university");
console.log(
"\nThe sum of the research papers per university:",
JSON.stringify(queryRes.rows, null, 2)
);

// Create a view for minimum of the h-index of all authors per university.
const CREATE_HINDEX_MIN_VIEW = `
CREATE OR REPLACE VIEW h_index_min AS
SELECT
university,
MIN(h_index) as min_h_index
FROM authors
GROUP BY university
`;

await client.query(CREATE_HINDEX_MIN_VIEW);
queryRes = await client.query("SELECT * FROM h_index_min");
console.log(
"\nThe minimum of the h-index of all authors per university:",
JSON.stringify(queryRes.rows, null, 2)
);

// Create a view for maximum of the h-index of all authors per university.
const CREATE_HINDEX_MAX_VIEW = `
CREATE OR REPLACE VIEW h_index_max AS
SELECT
university,
MAX(h_index) as max_h_index
FROM authors
GROUP BY university
`;

await client.query(CREATE_HINDEX_MAX_VIEW);
queryRes = await client.query("SELECT * FROM h_index_max");
console.log(
"\nThe maximum of the h-index of all authors per university:",
JSON.stringify(queryRes.rows, null, 2)
);

console.log("Database seeding completed successfully!");
} catch (error) {
console.error("Error seeding database:", error);
} finally {
await client.end();
}
}

// Execute the seeding function
createDBviews(client);
Loading