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
60 changes: 3 additions & 57 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,72 +1,18 @@
> If you are following the HackYourFuture curriculum we recommend you to start with module
> 1: [HTML/CSS/GIT](https://github.com/HackYourFuture/HTML-CSS). To get a complete overview of the HackYourFuture
> 1: [CLI/GIT](https://github.com/HackYourFuture/CLI-Git). To get a complete overview of the HackYourFuture
> curriculum first, click [here](https://github.com/HackYourFuture/curriculum).

> Please help us improve and share your feedback! If you find better tutorials or links, please share them
> by [opening a pull request](https://github.com/HackYourFuture/databases/pulls).

# Module #6 - Databases: Store and retrieve data with MySQL (Backend)
# Module #6 - Databases: Store and retrieve data with PostgreSQL (Backend)

![Databases](./assets/databases.png)

Have you ever thought about how your brain remembers things? It happens automatically for humans, but that's not the case for computers. Any time you go to a website and fill in some details in a form for example, that information needs to be saved somewhere. This "somewhere" is called a `database`.

In this module, you learn all about a fundamental part of any software application: how to (safely) store data, so that it can be used on-demand. You will learn how to structure and group data so that your apps know where to find and store the correct data.

## Before you start

**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](./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;
video: [MySQL Installation on Linux (Ubuntu)](https://www.youtube.com/watch?v=Y_LibBhOGOY)
- For MacOS, watch the following video: [Installing MySQL on MacOS](https://www.youtube.com/watch?v=HxCXyxFEA0s).

### Setup your first database

In this document, you find all the instructions on how to setup your first database. Most of the commands are done in the command line, so make sure you have yours open before you start.

**Step 1: Logging in with the `root` user**

To get started with your new MySQL client, we first have to login with the `root` user.

> A root user, also known as a `superuser` is a special user account that has access to all commands and files of any
> particular software.

In Windows OS, if you click on the Start menu and type `MySQL Command line Client`, then the MySQL Command Line Client gives you a `msql>` prompt after typing in your root password. Note that this password is the one you used for the `root user` of the MySQL during the installation. Linux and MAC users can execute `mysql -uroot -p` and then type your root password.

**Step 2: Creating a `hyfuser` account**

After loggin in with the root user, it's time to create the account that you will use for this module. Execute the following commands, one after the other:

```bash
# Step 1: This command creates a user 'hyfuser' with password 'hyfpassword' for the database server at 'localhost'

mysql> create user 'hyfuser'@'localhost' identified with mysql_native_password by 'hyfpassword';

# If this does not work try the alternative command:

mysql> create user 'hyfuser'@'localhost' identified by 'hyfpassword';

# Step 2: This command gives all permissions to user 'hyfuser'. The (*.*) means every table of every database.

mysql> grant all privileges on *.* to 'hyfuser'@'localhost';

# Step 3: This command flushes all privileges so that mysql reloads the grant table and our changes are enabled

msyql> flush privileges;

# Step 4: This command creates a database named 'userdb'

mysql> create database userdb;
```

**Step 3: Installing MySQL driver to use with Node.js**

We want to use MySQL with JavaScript and to this end, we use the following [package](https://github.com/mysqljs/mysql). You can create a project wherever you want and install it. To test that everything is working, you can use the `connection-test.js` file. If you run it it should output `The solution is: 2`.

## Learning goals

In this module, you get familiar with the complexity of storing data. By the end of it, you have learned:
Expand All @@ -75,7 +21,7 @@ In this module, you get familiar with the complexity of storing data. By the end
- How to work with `Structured Query Language` (SQL);
- All about the `relational model`;
- How to recognise the `basic setup of a database`;
- Know about `MySQL` as an example of a relational database system;
- Know about `PostgreSQL` as an example of a relational database system;
- Know `NoSQL` databases, with an emphasis on `MongoDB`.

## How to use this repository
Expand Down
100 changes: 93 additions & 7 deletions SQL-CHEATSHEET.md
Original file line number Diff line number Diff line change
@@ -1,28 +1,30 @@
# SQL Cheatsheet
# PostgreSQL Cheatsheet

## Queries
This cheat sheet provides a quick reference for common PostgreSQL SQL commands and operations.

## Basic Queries

### Specify what information to extract

```sql
SELECT column
```

## From which table
### From which table

```sql
FROM table
```

## Only extract rows where the condition holds
### Only extract rows where the condition holds

(Used with an operator: `>, <, >=, <=, =, <>, BETWEEN, LIKE, IN`)

```sql
WHERE column = 'value'
```

## Combining `WHERE` clauses:
### Combining `WHERE` clauses:

(Used with: `AND, OR`)

Expand All @@ -31,7 +33,7 @@ WHERE column = 'value' OR
column = 'other value'
```

## Aggregating results:
### Aggregating results:

(Used with: `SUM, COUNT, MIN, MAX, AVG`)

Expand All @@ -41,10 +43,94 @@ SELECT
FROM table
```

## Aliasing tables
### Aliasing tables

```sql
SELECT
column AS alias
FROM table
```

## PostgreSQL-Specific Features

### Common Data Types
```sql
SERIAL -- Auto-incrementing integer
VARCHAR(n) -- Variable-length string
TEXT -- Unlimited-length string
INTEGER -- 4-byte integer
BIGINT -- 8-byte integer
BOOLEAN -- TRUE/FALSE
TIMESTAMP -- Date and time
JSONB -- Binary JSON (recommended over JSON)
UUID -- Universally unique identifier
```

### Create Table with PostgreSQL Features
```sql
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
name TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
active BOOLEAN DEFAULT TRUE
);
```

### Insert with RETURNING
```sql
INSERT INTO users (email, name)
VALUES ('user@example.com', 'John Doe')
RETURNING id;
```

### UPSERT (Insert or Update)
```sql
INSERT INTO users (id, email, name)
VALUES (1, 'user@example.com', 'John Doe')
ON CONFLICT (id) DO UPDATE SET
email = EXCLUDED.email,
name = EXCLUDED.name;
```

### Parameterized Queries (for Node.js pg library)
```sql
-- In JavaScript: client.query('SELECT * FROM users WHERE id = $1', [userId])
SELECT * FROM users WHERE id = $1;
```

### JSON Operations
```sql
-- Query JSON data
SELECT data->>'name' FROM users WHERE data @> '{"active": true}';

-- Update JSON data
UPDATE users SET data = data || '{"last_login": "2023-01-01"}' WHERE id = 1;
```

### Common psql Commands
```sql
\l -- List databases
\c database -- Connect to database
\dt -- List tables
\d table -- Describe table
\q -- Quit psql
```

### Useful Functions
```sql
-- String functions
CONCAT(str1, str2) -- Concatenate strings
UPPER(string) -- Convert to uppercase
LOWER(string) -- Convert to lowercase
LENGTH(string) -- String length

-- Date functions
NOW() -- Current timestamp
CURRENT_DATE -- Current date
EXTRACT(YEAR FROM date) -- Extract part of date

-- Window functions
ROW_NUMBER() OVER (ORDER BY column) -- Row numbering
RANK() OVER (ORDER BY column) -- Ranking
```
94 changes: 94 additions & 0 deletions Week1/Hadidreem17/setup_meetup_db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
const { Client } = require("pg");

async function main() {
const client = new Client({
user: "hyfuser",
host: "localhost",
database: "postgres",
password: "hyfpassword",
port: 5432,
});

await client.connect();

console.log("Dropping database if exists...");
await client.query("DROP DATABASE IF EXISTS meetup");

console.log("Creating database meetup...");
await client.query("CREATE DATABASE meetup");

await client.end();


const meetupClient = new Client({
user: "hyfuser",
host: "localhost",
database: "meetup",
password: "hyfpassword",
port: 5432,
});

await meetupClient.connect();

console.log("Creating tables...");

await meetupClient.query(`
CREATE TABLE Invitee (
invitee_no SERIAL PRIMARY KEY,
invitee_name VARCHAR(100),
invited_by VARCHAR(100)
);
`);

await meetupClient.query(`
CREATE TABLE Room (
room_no SERIAL PRIMARY KEY,
room_name VARCHAR(100),
floor_number INT
);
`);

await meetupClient.query(`
CREATE TABLE Meeting (
meeting_no SERIAL PRIMARY KEY,
meeting_title VARCHAR(200),
starting_time TIMESTAMP,
ending_time TIMESTAMP,
room_no INT REFERENCES Room(room_no)
);
`);

console.log("Inserting sample data...");

await meetupClient.query(`
INSERT INTO Invitee (invitee_name, invited_by) VALUES
('Sara', 'Ali'),
('John', 'Lina'),
('Maya', 'Omar'),
('Noor', 'Samir'),
('Adam', 'Lara');ssss
`);

await meetupClient.query(`
INSERT INTO Room (room_name, floor_number) VALUES
('Blue Room', 1),
('Red Room', 2),
('Green Room', 1),
('Orange Room', 3),
('VIP Room', 5);
`);

await meetupClient.query(`
INSERT INTO Meeting (meeting_title, starting_time, ending_time, room_no) VALUES
('Tech Meetup', NOW(), NOW() + INTERVAL '2 hours', 1),
('Startup Pitch', NOW(), NOW() + INTERVAL '1 hour', 2),
('Workshop JS', NOW(), NOW() + INTERVAL '3 hours', 3),
('Design Basics', NOW(), NOW() + INTERVAL '4 hours', 4),
('AI Conference', NOW(), NOW() + INTERVAL '5 hours', 5);
`);

console.log("All done");
await meetupClient.end();
}

main();
Loading