Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Assignment w2 HANNA MELNYK #13

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
node_modules/
/*/.env
*/node_modules
*/node_modules/
**/*.DS_Store
**/*-secret.json
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ In this module, you learn all about a fundamental part of any software applicati

**Before** your first session, you need to install the necessary software: MySQL. This differs depending on your operating system.

During the installation of MySQL v8, in one of the last steps, you must configure the password encryption. Here is [a screenshot of the step](https://i.stack.imgur.com/nFnWV.jpg). **You must select _Legacy_ for all the given scripts to be able to connect.**
During the installation of MySQL v8, in one of the last steps, you must configure the password encryption. Here is [a screenshot of the step](./assets/MySQL-security-setup.jpg). **You must select _Legacy_ for all the given scripts to be able to connect.**

- For Windows, download the [MySQL Community Server](https://dev.mysql.com/downloads/mysql/);
- For Linux (Ubuntu), watch the following;
Expand Down
5 changes: 4 additions & 1 deletion Week1/.gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
package.json
package-lock.json
create-table.js
create-table.js


Week1/node_modules/
76 changes: 76 additions & 0 deletions Week1/exercise_1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
const mysql = require('mysql');

const connection = mysql.createConnection({
host: 'localhost',
user: 'hyfuser',
password: 'hyfpassword',
multipleStatements: true
});


/*Connect to SQL server*/
connection.connect(err => {
if (err) {
return console.error('Connection error: ' + err.stack);
}
console.log('Connected!');
});


/*SQL queries*/
const createDatabaseAndTables =
`DROP DATABASE IF EXISTS meetup;
CREATE DATABASE meetup;
USE meetup;

CREATE TABLE Invitee (
invitee_no INT AUTO_INCREMENT PRIMARY KEY,
invitee_name VARCHAR(100),
invited_by VARCHAR(100)
);

CREATE TABLE Room (
room_no INT AUTO_INCREMENT PRIMARY KEY,
room_name VARCHAR(50),
floor_number INT
);

CREATE TABLE Meeting (
meeting_no INT AUTO_INCREMENT PRIMARY KEY,
meeting_title VARCHAR(100),
starting_time DATETIME,
ending_time DATETIME,
room_no INT,
FOREIGN KEY (room_no) REFERENCES Room(room_no)
);

INSERT INTO Room (room_name, floor_number) VALUES
('Paris', 1),
('New York', 2),
('Tokyo', 3),
('London', 4),
('Berlin', 5);

INSERT INTO Invitee (invitee_name, invited_by) VALUES
('Victor Hugo', 'Alexandre Dumas'),
('Mark Twain', 'Henry James'),
('Haruki Murakami', 'Kenzaburo Oe'),
('Charles Dickens', 'Wilkie Collins'),
('Albert Einstein', 'Niels Bohr');

INSERT INTO Meeting (meeting_title, starting_time, ending_time, room_no) VALUES
('Literary Classics Discussion', '2024-08-01 09:00:00', '2024-08-01 10:00:00', 1),
('American Literature Seminar', '2024-08-02 11:00:00', '2024-08-02 12:00:00', 2),
('Japanese Fiction Workshop', '2024-08-03 14:00:00', '2024-08-03 15:00:00', 3),
('Victorian Literature Symposium', '2024-08-04 16:00:00', '2024-08-04 17:00:00', 4),
('Scientific Innovations Forum', '2024-08-05 13:00:00', '2024-08-05 14:00:00', 5);`;


// Execute the queries
connection.query(createDatabaseAndTables, (error, results, fields) => {
if (error) throw error;
console.log('Database and tables created, and data inserted');
});

// Close the connection
connection.end();
44 changes: 44 additions & 0 deletions Week1/exercise_2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const mysql = require('mysql');

const connection = mysql.createConnection({
host: 'localhost',
user: 'hyfuser',
password: 'hyfpassword',
database: 'world'
});

/*Connect to SQL server*/
connection.connect(err => {
if (err) {
return console.error('Connection error: ' + err.stack);
}
console.log('Connected!');
});


// Queries
const queries = [
"SELECT Name FROM country WHERE Population > 8000000;",
"SELECT Name FROM country WHERE Name LIKE '%land%';",
"SELECT Name FROM city WHERE Population BETWEEN 500000 AND 1000000;",
"SELECT Name FROM country WHERE Continent = 'Europe';",
"SELECT Name FROM country ORDER BY SurfaceArea DESC;",
"SELECT Name FROM city WHERE CountryCode = 'NLD';",
"SELECT Population FROM city WHERE Name = 'Rotterdam';",
"SELECT Name FROM country ORDER BY SurfaceArea DESC LIMIT 10;",
"SELECT Name FROM city ORDER BY Population DESC LIMIT 10;",
"SELECT SUM(Population) AS WorldPopulation FROM country;"
];


// Execute each query
queries.forEach((query, index) => {
connection.query(query, (error, results) => {
if (error) throw error;
console.log(`Query ${index + 1}:`);
console.log(results);
});
});

// End the connection
connection.end();
29 changes: 29 additions & 0 deletions Week2/connection_query.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//C:\Users\knowl\Documents\hyf\databases\Week2\connection_query.js
import mysql from 'mysql';

export const createNewConnection = () => {
return mysql.createConnection({
host: 'localhost',
user: 'hyfuser',
password: 'hyfpassword',
multipleStatements: true,
});
};

export const useDatabase = (connection) => {
return new Promise((resolve, reject) => {
const createDatabaseAndUse = `
CREATE DATABASE IF NOT EXISTS w2_research;
USE w2_research;
`;
connection.query(createDatabaseAndUse, (err, results) => {
if (err) {
console.error('Error creating or selecting database:', err.stack);
reject(err);
return;
}
console.log('Database selected successfully.');
resolve();
});
});
};
99 changes: 99 additions & 0 deletions Week2/exercise_1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
//C:\Users\knowl\Documents\hyf\databases\Week2\exercise_1.js
import {createNewConnection, useDatabase} from './connection_query.js';


const createAuthorsTable = (connection) => {
return new Promise((resolve, reject) => {
const createAuthorsTableQuery = `
CREATE TABLE IF NOT EXISTS authors (
author_id INT AUTO_INCREMENT PRIMARY KEY,
author_name VARCHAR(100) NOT NULL,
university VARCHAR(100),
date_of_birth DATE,
h_index INT,
gender ENUM('Male', 'Female', 'Other')
);
`;
connection.query(createAuthorsTableQuery, (err, results) => {
if (err) {
console.error('Error creating authors table:', err.stack);
reject(err);
return;
}
console.log('Authors table created.');
resolve();
});
});
};

const addMentorColumn = (connection) => {
return new Promise((resolve, reject) => {
const checkColumnExistsQuery = `
SELECT COUNT(*) AS columnExists
FROM information_schema.columns
WHERE table_name = 'authors'
AND column_name = 'mentor';
`;

connection.query(checkColumnExistsQuery, (err, results) => {
if (err) {
console.error('Error checking for mentor column:', err.stack);
reject(err);
return;
}

const columnExists = results[0].columnExists;

if (columnExists) {
console.log('Mentor column already exists. No changes made.');
resolve();
} else {
const addMentorColumnQuery = `
ALTER TABLE authors
ADD COLUMN mentor INT,
ADD CONSTRAINT fk_mentor
FOREIGN KEY (mentor) REFERENCES authors(author_id)
ON DELETE SET NULL
ON UPDATE CASCADE;
`;

connection.query(addMentorColumnQuery, (err, results) => {
if (err) {
console.error('Error adding mentor column:', err.stack);
reject(err);
return;
}
console.log('Mentor column added with foreign key constraint.');
resolve();
});
}
});
});
};


const exerciseOne = async () => {
const connection = createNewConnection();
connection.connect(err => {
if (err) {
return console.error('Connection error: ' + err.stack);
}
console.log('exercise_1: Connected!');
});


try {
await useDatabase(connection) ; // Select the database
await createAuthorsTable(connection) ; // Create the authors table
await addMentorColumn(connection) ; // Add the mentor column with foreign key

} catch (err) {
console.error('Failed to set up the database:', err);
} finally {
connection.end();
}
};


exerciseOne();

Loading