Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Week3/EX3-injection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const client = require('pg');

const client = new Client({
host: "localhost",
user: "hyfuser",
password: "hyfpass",
database: "world",
port: 5432,
});

client.connect();
async function getPopulation(countryTable, name, code) {
const sql = `
SELECT population
FROM ${countryTable}
WHERE name = $1 AND code = $2
`;
const values = [name, code];

const result = await client.query(sql, values);

if (!result || result.rows.length === 0) {
throw new Error('Not found');
}

return result.rows[0].population;
}
45 changes: 45 additions & 0 deletions Week3/Ex1-Normalization.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
-- 3NF Normalized Schema


CREATE TABLE members (
member_id INT PRIMARY KEY,
member_name VARCHAR(100) NOT NULL,
member_address VARCHAR(200) NOT NULL
);

CREATE TABLE venues (
venue_code VARCHAR(10) PRIMARY KEY,
venue_description VARCHAR(200) NOT NULL
);


CREATE TABLE dinners (
dinner_id VARCHAR(20) PRIMARY KEY,
dinner_date DATE NOT NULL,
venue_code VARCHAR(10) NOT NULL,
FOREIGN KEY (venue_code) REFERENCES venues(venue_code)
);


CREATE TABLE food (
food_code VARCHAR(10) PRIMARY KEY,
food_description VARCHAR(100) NOT NULL
);


CREATE TABLE dinner_food (
dinner_id VARCHAR(20),
food_code VARCHAR(10),
PRIMARY KEY (dinner_id, food_code),
FOREIGN KEY (dinner_id) REFERENCES dinners(dinner_id),
FOREIGN KEY (food_code) REFERENCES food(food_code)
);


CREATE TABLE member_dinner (
member_id INT,
dinner_id VARCHAR(20),
PRIMARY KEY (member_id, dinner_id),
FOREIGN KEY (member_id) REFERENCES members(member_id),
FOREIGN KEY (dinner_id) REFERENCES dinners(dinner_id)
);
Binary file added Week3/Ex1_Normalization-screenshot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Week3/Ex2-Transactions/account-chang.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Week3/Ex2-Transactions/balance-screenshot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
31 changes: 31 additions & 0 deletions Week3/Ex2-Transactions/create-tables.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import client from "./database.js";

async function createTables() {
await client.connect();

try {
await client.query(`
CREATE TABLE IF NOT EXISTS account (
account_number INT PRIMARY KEY,
balance NUMERIC(12,2) NOT NULL
);

CREATE TABLE IF NOT EXISTS account_changes (
change_number SERIAL PRIMARY KEY,
account_number INT NOT NULL,
amount NUMERIC(12,2) NOT NULL,
changed_date TIMESTAMP DEFAULT NOW(),
remark TEXT,
FOREIGN KEY (account_number) REFERENCES account(account_number)
);
`);

console.log("Tables created successfully");
} catch (err) {
console.error("Error creating tables:", err);
} finally {
await client.end();
}
}

createTables();
11 changes: 11 additions & 0 deletions Week3/Ex2-Transactions/database.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import pg from "pg";

const client = new pg.Client({
host: "localhost",
port: 5432,
user: "hyfuser",
password: "hyfpassword",
database: "bankdb",
});

export default client;
24 changes: 24 additions & 0 deletions Week3/Ex2-Transactions/insert-values.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import client from "./database.js";

async function insertValues() {
await client.connect();

try {
await client.query(`
INSERT INTO account (account_number, balance)
VALUES
(101, 5000),
(102, 3000)
ON CONFLICT (account_number) DO NOTHING;
`);

console.log("Sample accounts inserted");

} catch (err) {
console.error("Error inserting values:", err);
} finally {
await client.end();
}
}

insertValues();
49 changes: 49 additions & 0 deletions Week3/Ex2-Transactions/transaction.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import client from "./database.js";

async function doTransaction() {
await client.connect();

try {
await client.query("BEGIN");

const amount = 1000;
const fromAcc = 101;
const toAcc = 102;

// 1. Subtract from account 101
await client.query(
`UPDATE account SET balance = balance - $1 WHERE account_number = $2`,
[amount, fromAcc]
);

await client.query(
`INSERT INTO account_changes (account_number, amount, remark)
VALUES ($1, $2, 'Transfer to 102')`,
[fromAcc, -amount]
);

// 2. Add to account 102
await client.query(
`UPDATE account SET balance = balance + $1 WHERE account_number = $2`,
[amount, toAcc]
);

await client.query(
`INSERT INTO account_changes (account_number, amount, remark)
VALUES ($1, $2, 'Transfer from 101')`,
[toAcc, amount]
);

// If everything is OK → commit
await client.query("COMMIT");
console.log("Transaction completed successfully");

} catch (err) {
console.error("Transaction failed:", err);
await client.query("ROLLBACK");
} finally {
await client.end();
}
}

doTransaction();
Binary file added Week3/Ex3-injection-screenshot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion Week3/homework/mongodb/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
# - look up how to connect to your database in atlas, there is a nice `connect` button that will help you out
# - fill in the link to your new database. Make sure the database is `databaseWeek3`!

MONGODB_URL=mongodb+srv://<username>:<password>@<cluster>/databaseWeek3?retryWrites=true&w=majority
MONGODB_URL=mongodb+srv://asaadeddin87_db_user:<password>@<cluster_url>/databaseWeek3
2 changes: 2 additions & 0 deletions Week3/homework/mongodb/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.env
node_modules/
Binary file added Week3/homework/mongodb/Exe4-Screenshot .png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
111 changes: 44 additions & 67 deletions Week3/homework/mongodb/index.js
Original file line number Diff line number Diff line change
@@ -1,104 +1,81 @@
require('dotenv').config();
const { MongoClient, ServerApiVersion } = require("mongodb");

const { seedDatabase } = require("./seedDatabase.js");

async function createEpisodeExercise(client) {
/**
* We forgot to add the last episode of season 9. It has this information:
*
* episode: S09E13
* title: MOUNTAIN HIDE-AWAY
* elements: ["CIRRUS", "CLOUDS", "CONIFER", "DECIDIOUS", "GRASS", "MOUNTAIN", "MOUNTAINS", "RIVER", "SNOWY_MOUNTAIN", "TREE", "TREES"]
*/
const collection = client.db("databaseWeek3").collection("bob_ross_episodes");

const newEpisode = {
episode: "S09E13",
title: "MOUNTAIN HIDE-AWAY",
elements: ["CIRRUS", "CLOUDS", "CONIFER", "DECIDUOUS", "GRASS", "MOUNTAIN", "MOUNTAINS", "RIVER", "SNOWY_MOUNTAIN", "TREE", "TREES"]
};

// Write code that will add this to the collection!
const result = await collection.insertOne(newEpisode);

console.log(
`Created season 9 episode 13 and the document got the id ${"TODO: fill in variable here"}`
`Created season 9 episode 13 and the document got the id ${result.insertedId}`
);
}

async function findEpisodesExercises(client) {
/**
* Complete the following exercises.
* The comments indicate what to do and what the result should be!
*/

// Find the title of episode 2 in season 2 [Should be: WINTER SUN]

console.log(
`The title of episode 2 in season 2 is ${"TODO: fill in variable here"}`
);
const collection = client.db("databaseWeek3").collection("bob_ross_episodes");

// Find the season and episode number of the episode called "BLACK RIVER" [Should be: S02E06]
// Title of episode 2 in season 2
const ep2s2 = await collection.findOne({ episode: "S02E02" });
console.log(`The title of episode 2 in season 2 is ${ep2s2.title}`);

console.log(
`The season and episode number of the "BLACK RIVER" episode is ${"TODO: fill in variable here"}`
);

// Find all of the episode titles where Bob Ross painted a CLIFF [Should be: NIGHT LIGHT, EVENING SEASCAPE, SURF'S UP, CLIFFSIDE, BY THE SEA, DEEP WILDERNESS HOME, CRIMSON TIDE, GRACEFUL WATERFALL]

console.log(
`The episodes that Bob Ross painted a CLIFF are ${"TODO: fill in variable here"}`
);
// Season and episode of "BLACK RIVER"
const blackRiver = await collection.findOne({ title: "BLACK RIVER" });
console.log(`The season and episode number of the "BLACK RIVER" episode is ${blackRiver.episode}`);

// Find all of the episode titles where Bob Ross painted a CLIFF and a LIGHTHOUSE [Should be: NIGHT LIGHT]
// Episodes with CLIFF
const cliffEpisodes = await collection.find({ elements: "CLIFF" }).toArray();
console.log(`The episodes that Bob Ross painted a CLIFF are ${cliffEpisodes.map(e => e.title).join(", ")}`);

console.log(
`The episodes that Bob Ross painted a CLIFF and a LIGHTHOUSE are ${"TODO: fill in variable here"}`
);
// Episodes with CLIFF and LIGHTHOUSE
const cliffLighthouse = await collection.find({ elements: { $all: ["CLIFF", "LIGHTHOUSE"] } }).toArray();
console.log(`The episodes that Bob Ross painted a CLIFF and a LIGHTHOUSE are ${cliffLighthouse.map(e => e.title).join(", ")}`);
}

async function updateEpisodeExercises(client) {
/**
* There are some problems in the initial data that was filled in.
* Let's use update functions to update this information.
*
* Note: do NOT change the data.json file
*/
const collection = client.db("databaseWeek3").collection("bob_ross_episodes");

// Episode 13 in season 30 should be called BLUE RIDGE FALLS, yet it is called BLUE RIDGE FALLERS now. Fix that

console.log(
`Ran a command to update episode 13 in season 30 and it updated ${"TODO: fill in variable here"} episodes`
// Fix season 30 episode 13 title
const updateTitle = await collection.updateOne(
{ episode: "S30E13" },
{ $set: { title: "BLUE RIDGE FALLS" } }
);
console.log(`Ran a command to update episode 13 in season 30 and it updated ${updateTitle.modifiedCount} episodes`);

// Unfortunately we made a mistake in the arrays and the element type called 'BUSHES' should actually be 'BUSH' as sometimes only one bush was painted.
// Update all of the documents in the collection that have `BUSHES` in the elements array to now have `BUSH`
// It should update 120 episodes!

console.log(
`Ran a command to update all the BUSHES to BUSH and it updated ${"TODO: fill in variable here"} episodes`
// Replace BUSHES with BUSH
const updateBushes = await collection.updateMany(
{ elements: "BUSHES" },
{ $set: { "elements.$": "BUSH" } }
);
console.log(`Ran a command to update all the BUSHES to BUSH and it updated ${updateBushes.modifiedCount} episodes`);
}

async function deleteEpisodeExercise(client) {
/**
* It seems an errand episode has gotten into our data.
* This is episode 14 in season 31. Please remove it and verify that it has been removed!
*/
const collection = client.db("databaseWeek3").collection("bob_ross_episodes");

console.log(
`Ran a command to delete episode and it deleted ${"TODO: fill in variable here"} episodes`
);
const result = await collection.deleteOne({ episode: "S31E14" });
console.log(`Ran a command to delete episode and it deleted ${result.deletedCount} episodes`);
}

async function main() {
if (process.env.MONGODB_URL == null) {
throw Error(
`You did not set up the environment variables correctly. Did you create a '.env' file and add a package to create it?`
);
if (!process.env.MONGODB_URL) {
throw new Error("Please set MONGODB_URL in your .env file");
}

const client = new MongoClient(process.env.MONGODB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
serverApi: ServerApiVersion.v1
});

try {
await client.connect();

// Seed our database
// Seed database
await seedDatabase(client);

// CREATE
Expand All @@ -112,11 +89,11 @@ async function main() {

// DELETE
await deleteEpisodeExercise(client);

} catch (err) {
console.error(err);
} finally {
// Always close the connection at the end
client.close();
await client.close();
}
}

Expand Down
Loading