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
75 changes: 75 additions & 0 deletions Week3/assignment3/answers ex1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
✅ 3.1 – Normalization Exercise
Which columns violate 1NF?

1NF requires:

No repeating groups

No multivalued attributes

Atomic values

Violations:

food_code → contains multiple codes (e.g., C1, C2)

food_description → contains multiple values (e.g., Curry, Cake)

dinner_date → inconsistent date formats (not strictly 1NF violation, but bad practice)

2. Extracted Entities

Member

Dinner

Venue

Food

Member–Dinner (many-to-many)

Dinner–Food (many-to-many)

3. 3NF Tables
Member

member_id (PK)

member_name

member_address

Venue

venue_code (PK)

venue_description

Dinner

dinner_id (PK)

dinner_date

venue_code (FK → Venue)

Food

food_code (PK)

food_description

MemberDinner

member_id (FK)

dinner_id (FK)
PK: (member_id, dinner_id)

DinnerFood

dinner_id (FK)

food_code (FK)
PK: (dinner_id, food_code)
41 changes: 41 additions & 0 deletions Week3/assignment3/exercise2/transaction.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const mysql = require("mysql2/promise");

async function main() {
const conn = await mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "bankdb",
});

try {
await conn.beginTransaction();

// debit sender
await conn.execute(`
UPDATE account SET balance = balance - 1000 WHERE account_number = 101
`);

// credit receiver
await conn.execute(`
UPDATE account SET balance = balance + 1000 WHERE account_number = 102
`);

// log changes
await conn.execute(
`INSERT INTO account_changes (account_number, amount, remark)
VALUES (101, -1000, 'Money transferred to 102'),
(102, 1000, 'Money received from 101')`
);

await conn.commit();
console.log("Transaction completed.");
} catch (err) {
await conn.rollback();
console.error("Transaction rolled back:", err);
}

conn.end();
}

main();
33 changes: 33 additions & 0 deletions Week3/assignment3/exercise2/transactions-create-tables.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const mysql = require("mysql2/promise");

async function main() {
const conn = await mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "bankdb",
});

await conn.execute(`
CREATE TABLE IF NOT EXISTS account (
account_number INT PRIMARY KEY,
balance DECIMAL(10,2) NOT NULL
)
`);

await conn.execute(`
CREATE TABLE IF NOT EXISTS account_changes (
change_number INT AUTO_INCREMENT PRIMARY KEY,
account_number INT,
amount DECIMAL(10,2),
changed_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
remark VARCHAR(255),
FOREIGN KEY (account_number) REFERENCES account(account_number)
)
`);

console.log("Tables created.");
conn.end();
}

main();
20 changes: 20 additions & 0 deletions Week3/assignment3/exercise2/transactions-insert-values.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const mysql = require("mysql2/promise");

async function main() {
const conn = await mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "bankdb",
});

await conn.execute(
`INSERT INTO account (account_number, balance)
VALUES (101, 5000), (102, 2000)`
);

console.log("Sample data inserted.");
conn.end();
}

main();
7 changes: 7 additions & 0 deletions Week3/assignment3/exercise4/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# This is an example .env file. We use .env files to store data that describes the environment the code needs to run on.
# For this exercise we need a MONGODB_URL, so:
# - make a copy of this file, call it `.env`
# - 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://Dalia:Dal12345@sad@cluster0.aov8qkx.mongodb.net/?appName=Cluster0
File renamed without changes.
143 changes: 143 additions & 0 deletions Week3/assignment3/exercise4/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
require("dotenv").config();
const { MongoClient, ServerApiVersion } = require("mongodb");
const { seedDatabase } = require("./seedDatabase.js");

async function createEpisodeExercise(client) {
// Add season 9 episode 13
const newEpisode = {
episode: "S09E13",
title: "MOUNTAIN HIDE-AWAY",
elements: [
"CIRRUS", "CLOUDS", "CONIFER", "DECIDIOUS", "GRASS",
"MOUNTAIN", "MOUNTAINS", "RIVER", "SNOWY_MOUNTAIN",
"TREE", "TREES"
]
};
const result = await client
.db("databaseWeek3")
.collection("bob_ross_episodes")
.insertOne(newEpisode);

console.log(
`Created season 9 episode 13 and the document got the id ${result.insertedId}`
);
}

async function findEpisodesExercises(client) {
const collection = client.db("databaseWeek3").collection("bob_ross_episodes");

// 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}`);

// Episode called 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}`
);

// All episodes where Bob Ross painted a 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(", ")}`
);

// All episodes where Bob Ross painted both a CLIFF and a LIGHTHOUSE
const cliffLighthouseEpisodes = await collection
.find({ elements: { $all: ["CLIFF", "LIGHTHOUSE"] } })
.toArray();
console.log(
`The episodes that Bob Ross painted a CLIFF and a LIGHTHOUSE are ${cliffLighthouseEpisodes
.map((e) => e.title)
.join(", ")}`
);
}

async function updateEpisodeExercises(client) {
const collection = client.db("databaseWeek3").collection("bob_ross_episodes");

// Correct the title of episode S30E13
const updateEpisode = 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 ${updateEpisode.modifiedCount} episodes`
);

// Change all elements labeled BUSHES to 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) {
const collection = client.db("databaseWeek3").collection("bob_ross_episodes");

// Delete episode S31E14
const deleteResult = await collection.deleteOne({ episode: "S31E14" });
console.log(
`Ran a command to delete episode and it deleted ${deleteResult.deletedCount} episodes`
);
}

async function main() {
if (!process.env.MONGODB_URL) {
throw Error(
"You did not set up the environment variables correctly. Please create a '.env' file."
);
}

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


try {
await client.connect();

// Seed the database
await seedDatabase(client);

// CREATE
await createEpisodeExercise(client);

// READ
await findEpisodesExercises(client);

// UPDATE
await updateEpisodeExercises(client);

// DELETE
await deleteEpisodeExercise(client);
} catch (err) {
console.error(err);
} finally {
await client.close();
}
}

main();


/**
* In the end the console should read something like this:

Created season 9 episode 13 and the document got the id 625e9addd11e82a59aa9ff93
The title of episode 2 in season 2 is WINTER SUN
The season and episode number of the "BLACK RIVER" episode is S02E06
The episodes that Bob Ross painted a CLIFF are NIGHT LIGHT, EVENING SEASCAPE, SURF'S UP, CLIFFSIDE, BY THE SEA, DEEP WILDERNESS HOME, CRIMSON TIDE, GRACEFUL WATERFALL
The episodes that Bob Ross painted a CLIFF and a LIGHTHOUSE are NIGHT LIGHT
Ran a command to update episode 13 in season 30 and it updated 1 episodes
Ran a command to update all the BUSHES to BUSH and it updated 120 episodes
Ran a command to delete episode and it deleted 1 episodes

*/
Loading