Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1268577

Browse files
authored
Merge pull request HackYourFuture#191 from HackYourFuture/unmesh
Week2 material and homework
2 parents 724aebe + 9f14cff commit 1268577

File tree

8 files changed

+5617
-239
lines changed

8 files changed

+5617
-239
lines changed

Week1/databases/world.sql

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@
1515
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
1616
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
1717

18-
DROP SCHEMA IF EXISTS world;
19-
CREATE SCHEMA world;
20-
USE world;
18+
DROP SCHEMA IF EXIST new_world;
19+
CREATE SCHEMA new_world;
20+
USE new_world;
2121
SET AUTOCOMMIT=0;
2222

2323
--

Week2/MAKEME.md

Lines changed: 39 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,40 @@
11
# Homework week 2
2-
3-
## Writing a model to communicate with the TODO database
4-
5-
Look at [todo_app/db.sql](./todo_app/db.sql) and use it to create a database. In
6-
the [todo_app/program.js](./todo_app/program.js) file there's a little program
7-
that should be able to extract TODOs from the database, update them, and delete
8-
them. The `load` function already extracts all TODOs from the database.
9-
10-
Run `npm install` inside the `todo_app` directory to download and install the MySQL
11-
connector.
12-
13-
Try to understand what happens in this program. How is the database connection
14-
created? How do we use the connection to query the database?
15-
16-
You'll find the following empty functions in the `program.js` file, please
17-
implement them:
18-
19-
*Read how to [use and escape query values](https://github.com/mysqljs/mysql#escaping-query-values)*
20-
21-
```js
22-
class TodoModel {
23-
24-
// ...
25-
26-
create(description, callback) {
27-
// Write code and query to create a new TODO item
28-
}
29-
30-
update(id, description, callback) {
31-
// Write code and query to update and existing TODO item
32-
}
33-
34-
delete(id, callback) {
35-
// Write code and query to delete an existing TODO item
36-
}
37-
38-
tagTodoItem(todoItemId, tagId, callback) {
39-
// Write code and query add a tag to a TODO item
40-
}
41-
42-
untagTodoItem(todoItemId, tagId, callback) {
43-
// Write code and query remove a tag from a TODO item
44-
}
45-
46-
markCompleted(todoItemId, callback) {
47-
// Write code to mark a TODO item as completed
48-
}
49-
}
50-
```
51-
52-
# Adding a new database user
53-
54-
Until now we've always connected to the database as `root`. We don't want to
55-
allow our TODO app access to other databases than the TODO app itself:
56-
57-
- Figure out how to create a new user in MySQL.
58-
- Restrict the access for that user to only the `todo_app` database.
59-
- Use the newly created user credentials (username, password) in the connector of
60-
the `program.js` file.
2+
The homework contains 3 parts
3+
4+
## Part 1 : More SQL queries through JS program
5+
Write a node-JS program to get answers of following queries
6+
on the **new_world** database: Note that you are expected to get the input from user
7+
and use **prepared** statements to write the queries.
8+
9+
Hint: use [this] (https://github.com/mysqljs/mysql) link to read more
10+
about prepared statements.
11+
12+
1. What is the capital of country X ? (Accept X from user)
13+
2. List all the languages spoken in the region Y (Accept Y from user)
14+
3. Find the number of cities in which language Z is spoken (Accept Z from user)
15+
4. Are there any countries that have
16+
A) Same official language
17+
B) Same region
18+
If yes, display those countries.
19+
If no, display TRUE or FALSE
20+
5. List all the continents with the number of languages spoken in each continent
21+
22+
23+
## Part 2 : SQL research
24+
I want to get alerts when a country has >= 10 languages.
25+
E.g. If a country X has 9 languages in the CountryLanguage table,
26+
and a user INSERTs one more row in the CountryLanguage table, then I should get an alert.
27+
*How can I achieve this ?*
28+
- Write the necessary SQL statements for this solution and
29+
- Test your solution with example insert statements.
30+
31+
## Part 3 : Database design
32+
I want to develop a ToDo app in which a user can create a multiple
33+
ToDo lists with different purposes. Each list has at least one item.
34+
Each item can be tagged. Each item can be marked completed.
35+
There could be reminders for some items.
36+
37+
- Draw an Entity Relationship Diagram for the database of the ToDo App.
38+
39+
Read about Entity-relationship diagrams on the Internet
40+
E.g. [here] (https://www.lucidchart.com/pages/er-diagrams)

Week2/README.md

Lines changed: 88 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,100 @@
1-
# Lesson 2: Practical Database Usage
1+
# Lesson 2: Group by, Having and Joins. Promisification of JS client with prepared statements
22

3-
In this class, students will learn how to use more complex SQL queries to retrieve information across tables, and interact with data including write operations.
4-
5-
Objective: Students should be able to build CRUD functionality using SQL statements, including INSERT INTO, UPDATE, etc.
3+
Objective: This class introduces more clauses (group by, having) in the
4+
select statement. MySQL joins (inner, self, left and right) should be explained
5+
with demonstration (Employee table with **reportsTo** field and Department
6+
table with its PK in Employee table is suitable for this demonstration).
7+
Promise based JavaScript program with SQL prepared statements should be
8+
understood by students. The program can be found in the Week2 folder (Credits:
9+
@remarcmij)
610

711
## Pre-Class Readings
812

913
Before arriving to class on Sunday, please watch all of the videos in [this video playlist](https://www.lynda.com/SharedPlaylist/0d62f3e4428e44ada89466cdbc296fc0) on Lynda.
10-
- Inserting, Updating, and Deleting
11-
- Understanding Write Conflicts
12-
- Planning Your Database
13-
- The Data Definition Language
14-
- Understanding Stored Procedures and Injection Attacks
1514

1615
Also, please read the following page that explains the ACID database model.
1716
- [The ACID Database Model](https://www.thoughtco.com/the-acid-model-1019731)
1817

19-
## Main Topics
20-
21-
- INSERT INTO
22-
- UPDATE
23-
- DELETE
24-
- Writing SQL in your application
25-
- Raw SQL strings
26-
- Parameter validation
27-
- Escaping
28-
- Prepared statements
29-
- Stored procedures
30-
- Security
31-
- SQL Injection
32-
- User GRANTS
33-
- Enumeration
18+
## Topics to be covered
19+
20+
### NOT NULL and default values in CREATE table statement
21+
22+
Following links are worth reading.
23+
- [Working with nulls] (https://dev.mysql.com/doc/refman/8.0/en/working-with-null.html)
24+
- [TO DEFAULT or TO NULL] (https://blog.jooq.org/2014/11/11/have-you-ever-wondered-about-the-difference-between-not-null-and-default/)
25+
26+
### foreign key
27+
28+
Creating foreign key while creating the table
29+
```
30+
CREATE TABLE Employee (
31+
other fields,
32+
dept_id int,
33+
foreign key (dept_id)
34+
references Department(id)
35+
);
36+
```
37+
38+
Creating the foreign key by explicitly adding the constraint
39+
```
40+
ALTER TABLE Employee ADD CONSTRAINT fk_dept foreign key (dept_id) references Department(id);
41+
```
42+
43+
44+
### Database dump
45+
46+
A database dump (aka SQL dump) contains a record of the table structure
47+
and/or the data from a database and is usually in the form of a list of SQL statements.
48+
(An example file named `world.sql` is present in the Week2 folder)
49+
50+
- Collecting the dump of an existing database from terminal `mysqldump -uroot -p database > dump-file.sql`
51+
- Applying the dump from mysql command prompt `source /path/to/the/dump/file`
52+
- Applying the dump from the terminal `mysql -uroot -p [database] < /path/to/the/dump/file`
53+
54+
### Group by and Having clauses
55+
56+
- *Group by* clause is used to group rows with same values.
57+
- It can be used in conjunction with aggregate functions (E.g. min, max).
58+
- The queries that contain the *group by* clause only return a single row for every grouped item.
59+
- *Having* clause restricts the query results of *group by* clause.
60+
61+
### INSERT INTO table SET syntax
62+
63+
```
64+
INSERT INTO Department SET dept_id=101, dept_name='fun', dept_head='unmesh';
65+
```
66+
### Promise based program demo
67+
68+
The program is called `async-create-insert.js` and can be found in Week2 folder.
69+
- async : to create asynchronous function and ensure they return promise without having to worry
70+
about building those promises
71+
- await : to call a function returning promise without having to call .then() over that promise
72+
- promisify() : to convert a callback based function to a promise based one.
73+
74+
### Relationships between tables : 1-M, M-M
75+
76+
- One to One (one user has one profile)
77+
- One to Many (one department has many employees)
78+
- Many to Many (book(s) and author(s))
79+
80+
### Adding a column to the table
81+
```
82+
alter table Employee add column dept_id int
83+
```
84+
85+
### Update table (add a department head for a department)
86+
87+
```
88+
update Department set dept_head = 'Lucas' where dept_id = 3;
89+
```
90+
91+
### JOINs : CROSS, left, right, self, inner
92+
93+
- A comma (,) after **FROM** is equivalent to the CROSS join.
94+
- Implicit inner join (when the keyword **JOIN** is not used), **WHERE** clause has conditions.
95+
- self join use case : Employee table with (*eid* field and *reports_to* field)
96+
- left and right join : reverse of each other
97+
- [Join manual](https://dev.mysql.com/doc/refman/8.0/en/join.html)
3498

3599
## Reference Material
36100

Week2/async-create-insert.js

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
const util = require('util');
2+
const mysql = require('mysql');
3+
4+
const connection = mysql.createConnection({
5+
host: 'localhost',
6+
user: 'hyfuser',
7+
password: 'hyfpassword',
8+
database: 'class17',
9+
});
10+
11+
// Promisify the bind function of query function of connection object
12+
// Pass connection object (because bind expects "this")
13+
// Afterwards execQuery will work as a function that returns a promise but
14+
// we don't have to call "then" over that promise
15+
const execQuery = util.promisify(connection.query.bind(connection));
16+
17+
async function seedDatabase() {
18+
const CREATE_STUDENTS_TABLE = `
19+
CREATE TABLE IF NOT EXISTS students (
20+
student_number INT,
21+
student_name VARCHAR(50),
22+
date_of_birth DATE,
23+
grade FLOAT,
24+
gender ENUM('m', 'f')
25+
);`;
26+
const CREATE_TEACHERS_TABLE = `
27+
CREATE TABLE IF NOT EXISTS teachers (
28+
teacher_number INT,
29+
teacher_name VARCHAR(50),
30+
date_of_birth DATE,
31+
subject TEXT,
32+
gender ENUM('m', 'f')
33+
);`;
34+
const students = [
35+
{
36+
student_number: 4444,
37+
student_name: 'Benno',
38+
date_of_birth: '1995-04-26',
39+
grade: 8.3,
40+
gender: 'm',
41+
},
42+
{
43+
student_number: 3333,
44+
student_name: 'Henriata',
45+
date_of_birth: '1998-05-12',
46+
grade: 8.5,
47+
gender: 'm',
48+
},
49+
];
50+
51+
connection.connect();
52+
53+
try {
54+
// call the function that returns promise
55+
await execQuery(CREATE_STUDENTS_TABLE);
56+
await execQuery(CREATE_TEACHERS_TABLE);
57+
students.forEach(async student => {
58+
await execQuery('INSERT INTO students SET ?', student);
59+
});
60+
} catch (error) {
61+
console.error(error);
62+
}
63+
64+
connection.end();
65+
}
66+
67+
seedDatabase();

Week2/todo_app/db.sql

Lines changed: 0 additions & 62 deletions
This file was deleted.

Week2/todo_app/package.json

Lines changed: 0 additions & 19 deletions
This file was deleted.

0 commit comments

Comments
 (0)