0% found this document useful (0 votes)
14 views55 pages

Intro TODatabases

This document provides an introduction to databases, covering definitions, advantages, and the steps involved in database design, including conceptual, logical, and physical models. It also discusses the Entity-Relationship model, relational models, normalization, and SQL, including data definition language (DDL) and constraints. The document includes quizzes for assessment throughout the sections to reinforce learning.

Uploaded by

Wissem Chehaider
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views55 pages

Intro TODatabases

This document provides an introduction to databases, covering definitions, advantages, and the steps involved in database design, including conceptual, logical, and physical models. It also discusses the Entity-Relationship model, relational models, normalization, and SQL, including data definition language (DDL) and constraints. The document includes quizzes for assessment throughout the sections to reinforce learning.

Uploaded by

Wissem Chehaider
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Introduction to Databases

Introduction and Objectives


Database Introduction
At the end of this Chapter, the learner will be able to:

 Define a database
 Illustrate the advantages of using databases
 List the main steps to design a database

What is database
File System Drawbacks
 Data Redundancy: Data redundancy often requires higher storage
costs and poor access time.
 Data Inconsistency: Data Inconsistency is caused by data
Redundancy. It happens when similar data is stored in different
formats in more than one file.
 Data Isolation: Data isolation occurs in writing new applications
when retrieving data which can be stored in different format and
files
DataBase definition
 Structured set of information designed and produced to be easily
accessed, managed and modified by several users.
 A DataBase Management System (DBMS) is used to store
information in a database. Using a DBMS, we can find, sort,
transform and select information stored in database.

Fill in the blanks Solution


Data Redundancy requires higher storage costs and poor access time. Data
inconsistency happens when similar data is stored in different formats in more than
one file. Data Isolation occurs when retrieving data and data is stored in different
format and files

What is Database Management


System (DBMS)
Relational DataBase Management
Systems (RDBMS)
Using RDBMS allows us to:

 No Data redundancy
 Data Consistency and Integrity
 Easy access to data
 More flexibility than files
 Recovery process
Examples of RDBMS’s
There is so many Relational Database management systems. For this, it is
important to find a way for them to communicate

Assessment: Quiz
Which of the following is not an RDBMS

Oracle MySQL MongoDB


Which of the following are database advantages

Data redundancy Data Inconsistency Easy access to data Recovery


process
Is Data Redundancy one of database advantages

Yes No

Database Design
Database design
To design a database, it is important to follow 3 main steps:
Conceptual Model
 A conceptual model is a graphic representation that serves to
describe the functioning of a Database.
 It represents the main objects contained in the database, their
characteristics and the relationships established between these
different objects.
 This representation is normalized according to a well-defined
modeling.
 The conceptual model is independent from DBMS.

Logical Relational model


 A logical model or relational schema is a data representation model
that adds more information to the conceptual model based on
several rules.
 The logical model illustrates the data elements structure and set the
relationships between these different elements.
 The logical model is independent from the DBMS
Physical model
 The physical data model or physical schema is an implementation of
the logical data model in a specific RDBMS.
 It represents the structure and content of the database (tables,
columns, data types, constraints, etc.).
 The physical model is dependent from the DBMS

Assessment: Quiz
Which of the following is the best order of database design steps

logic, conceptual, physical model physical, relational, conceptual model


conceptual, logical, physical model conceptual, physical, relational model
Which of the following steps depends on RDBMS

Conceptual Logic Physical


The conceptual model adds more information to the logical model based on several
rules.
True False

Conclusion
Recap
 A database is an organized set of data stored and managed using a
DBMS.
 To design a database, we must follow 3 main steps:
o Create the conceptual data model
o Create the logical data model
o Create the physical model based on a DBMS

Entity-relationship model

Entity-relationship Model Introduction


Introduction
At the end of this Chapter, the learner will be able to:

 Learn how to convert functional needs to a conceptual data model


 Identify the main concepts of the Entity-relationship model

Entity
Entity / Relationship model
 The Entity-relationship model is a type of conceptual diagram widely
used for databases data, including relational databases.
 It is a tool for describing the structure of a database by highlighting
many concepts:
o Entity
o Relation
o Cardinalities
o Attributes / Identifier
o etc.

Entity
 An entity is an abstract representation of a real world object.
 An entity represents a physical or logical object.
 The object which will be represented with an entity must have
different characteristics.

Attributes
 Each entity is described based on a list of properties which
characterize the entity.
 At this level, the attributes are defined with their names
(designation). It is not necessary to identify types of the different
attributes

Entity Identifier
 An entity identifier is a property (attribute) which can qualify an
occurrence of an entity.
 The entity identifier can be simple or composed of multiple
attributes.
 An entity identifier is assigned to each entity upon creation.
Assessment: Quiz
Which from the following is true according to entity relationship diagram

It is a logical model It is a physical model It is a conceptual model


Choose the correct sentence

An entity can only have one identifier. An entity identifier is assigned to each
entity upon creation.
An entity identifier should be simple

True False

Relationship
Relationship
 A relationship represents links between entity occurrences.
 Several employees works in the department “department_1”.
 The relationship models the relation or association between
department and employee entities

Relationship
A relationship can have more information (attributes)

Cardinalities
 Cardinalities are among the properties of an association.
 In DBMS, cardinality refers to the relationship between two entities.
We should have two terms of cardinalities, on the side of each
entity.
 It models the number of times (minimum-maximum) of participation
of the entity in the relationship.
 The minimum value is either 0 or 1 and the maximum value varies
between 1 and N

 One employee works in one department


 A department hires between one and N employees
 There are 4 types of cardinalities : 0..1, 0..N, 1..1, 1..N

Relationship types
 The type of a given relationship can be identified based on the
cardinalities of each side.
 There are 3 types of relationship:
o OnetoOne (1..1)
o OnetoMany (1..N)
o ManytoMany (N..N)

Works_for” is OnetoMany relationship.

Assessment: Quiz
Which from the following is not a relationship type

OnetoOne ManytoOne ManytoMany OnetoMany


Which from the following is not a cardinality type

0..1 1..0 1..1


A relationship represents links between

entities relations

Other types of entities and


relationships
Sub-Entity
 A sub-entity expresses the notion of inheritance.
 Sub-entities inherit attributes from the parent class with some
specifications which are those attributes.
Weak entity
 An entity that cannot be uniquely identified by its own attributes and
relies on the relationship with other entity is called weak entity.
 A weak entity is an entity without identifier which depends on
another so-called strong entity.
 The weak entity is represented by a double rectangle.

Reflexive relation
A reflexive association is a binary association which involves the same
entity twice.
n-ary relationship
 In an n - ary relationship, the n shows the number of entities in the
relationship.
 If n=1, we get a reflexive relation, if n=2, it is a binary relation which
links between 2 entities.
 if n>2, we talk about n-ary relationship, which involves three or
more entities.

Assessment: Quiz
A sub-entity represents the concept of:

Aggregation Inheritance composition conceptual, physical, relational


model
In n-ary relationship, there are

n entities n relationships n entities and relationships


A weak entity is independent

True False
Conclusion
RECAP
 The entity relationship model is a conceptual model
 The entity relationship model is based on:
o Entities (Attributes and identifier)
o Relationships which links between entities
o Cardinalities
o Relationship types

Relational model

Relational Model Introduction


Introduction
At the end of this Chapter, the learner will be able to:

 Learn how to convert a conceptual model to a relational model


 Identify the different rules to perform this conversion

Relational model
Relational model
 The relational model is the second step in database designing.
 It consists on converting the conceptual model (the Entity-
relationship model) to a relational model based on several rules.

Relational model: main concepts


 A relational model is composed of relations (tables)
 Each relation has each own properties or attributes ( column names)
 Each relation should have an identifier (primary key) which can be
simple or composed.
 A relation can reference to another relation using a foreign key,
which is the primary key of the referenced relation.
 The identifier of each relation must be underlined
 The foreign keys must be preceded or followed by a #

Assessment: Quiz
In database designing, relational model is

The first step The second step The third step


Each entity and relationship will be converted to relations

True False
Each relation must have:
an identifier properties a foreign key

Mapping Rules
Mapping Rules: Entity
Entity (ER model) ⇒ Relation (Relational model)

Mapping rules: OnetoMany


 Relation (ER model) ⇒ Relation (Relational model)

Mapping rule: Relation OnetoOne


Mapping rule: Relation ManytoMany

Assessment: Quiz
Which of the following is the correct relational model according to the following entity
relationship model (( https://i.imgur.com/Z7pXRSr.png ))

Customers (CustCode, custName, custAdress, custTel) Orders (OrderCode,


OrderDate) Customers (CustCode, custName, custAdress, custTel) Orders
(OrderCode, OrderDate, #CustCode) Customers (CustCode, custName,
custAdress, custTel, #CustCode) Orders (OrderCode, OrderDate)
Mapping Rules specific cases
Mapping rule : Reflexive relation

Mapping rule: Weak entity

Mapping rule: SubEntity


Assessment: Quiz
How to convert a ManytoMany relationship::

A new relation will be created in which the primary key is composed of the
primary keys of the involved entities Each primary key of each entity should
migrate to the other entity
To convert the subentity, we should

create a new relation migrate its primary key to the parent entity
The identifier of a converted weak entity should be:

simple composed

Normalization
Normalization
 Normalization or Standardization consists on fixing rules on data
structure in order to respect the consistency of the data and avoid
any information redundancy.
 The main aim of normalization is to design a consistent database.
 Some constraints called “Normal Forms (NF) “ have to be
respected to have a normalized relational model.
 These Normal Forms are based on Functional Dependencies
(FD).
Normalization
Normalization eliminates redundancies, which allows:

 A decrease in the size of the database on disk


 Reduced risk of inconsistency
 Avoid multiple updates of the same data

Functional Dependencies (FD)


 X is in functional dependence on Y if to any value of the property Y
we can only match one value of the property X.
 If we know the value of Y, we can deduce Y single value from X (the
opposite is not true)

Functional Dependencies : Example

 There is a FD between Employee_id and Employee_name


 If we know the value of “employee_id”, we can identify the value of
“employee_name”

Assessment: Quiz
Which is true about DF:

X is in functional dependence on Y if to any value of the property Y we can only


match one value of the property X. X is in functional dependence on Y if to any
value of the property Y we can match more than one value of the property X.
Which is true about Normalization:

it increases in the size of the database on disk It reduce risk of inconsistency


Normalization consists on fixing rules on:

data structure data values

Normal forms
Normal Forms
The normalization is based on 3 normal forms which should be respected.
It consists on applying several rules to have a normalized relational model
1st Normal Form (1NF)
Each attribute needs to be simple not composed.

1st Normal Form (1NF)


Each relation attribute should contain a single value.

2nd Normal Form (2NF)


 Rule1: must be in 1NF
 Rule2: Non key attribute must depend on the entire key
3rd Normal Form (3NF)
 Rule1: must be in 2NF
 Rule2: No FD between non key attributes

Fill in the blanks Solution


In the 1st NF, each attribute must be simple and should have a single value. In the
2nd NF, relations must be in the 1st NF and non key attribute must depend on the
entire key In the 3rd NF, relations must be in in the 2st NFand non key attribute
must have no DF between them

Conclusion
Recap
 The entity relationship model should be converted to a relational model
based on several rules
 The relational model is based on:
o Relations
o Primary and Foreign Key
o Cardinalities and relation types
o Mapping rules
o Normalization and Normal Forms
Data definition language (DDL)

Data definition language (DDL)


Introduction
Introduction
At the end of this Chapter, the learner will be able to:

 Identify the SQL sublanguages


 Create a table
 Identify the different table constraints
 Create, update and drop a constraints
 Alter and drop a table

SQL Introduction
SQL Definition

 The physical data model consists of setting up a database in an


RDBMS.
 The language used for this type of operation is SQL (Structured
Query Language).
 SQL is composed of :
o Data Definition language (DDL)
o Data Manipulation Language (DML)
o Data Query Language (DQL)
o Data Control Language (DCL)
SQL definition
SQL is the standard language for RDBMS that provides a set of facilities for
query, data structure creation, data manipulation and data control.
CREATE TABLE Customer (

customerID NUMBER CHECK (customerID > 0) PRIMARY KEY,

name VARCHAR(30) NOT NULL,

street VARCHAR(30) NOT NULL,

postcode NUMBER CHECK (postcode > 0),

city VARCHAR(20)

);

Assessment: Quiz
SQL is:

System Query Language Structured Quality Language Structured Query


Language System Quality Language
Among these propositions which is not an SQL sub-language:

Data Query Language Data Definition Language Data Modifying Language


Data Manipulation Language
SQL is used in:

Conceptual model logical model physical model

Create data structure


Data types
There is a non-exhaustive list of data types used in SQL. The most used
ones are illustrated in the table below.
Create table
Syntax
CREATE TABLE table_name (

column1 data_type(size),

column2 data_type(size),

column3 data_type(size),

....

);

Create table
Example
CREATE TABLE STUDENT (

Student_id NUMBER(7),

Student_name VARCHAR2(20),

DateOfBirth DATE

);

DESCRIBE (or DESC ) Student; In order to show table structure

Assessment: Quiz
Which of the following command is correct to create the table product based on this
structure: Product (Product_id, Product_name, Price) ((
https://i.imgur.com/lSzRyGn.png ))
CREATE TABLE Product ( Product_id NUMBER, Product_name VARCHAR2(50),
Price Number(6,2) ); CREATE TABLE Product ( Product_id VARCHAR2(50),
Product_name VARCHAR2(50), Price Number(6,2) );
CREATE TABLE Product ( Product_id NUMBER, Product_name NUMBER, Price
Number(6,2) );

Constraints
Constraints definition
 Constraints are different rules enforced on the data columns of a table.
 Constraints are used to limit the type of data that can be stored into a
table.
 Constraints could be defined either on a column level or a table level.
 The column level constraints are applied directly to the column definition,
whereas the table level constraints are applied after identifying the whole
columns.

Constraint types
 The list of constraints and their descriptions are presented in the the table
below.

Assessment: Quiz
Choose the best alternative SQL constraints are applied to

Table name Table columns Columns types


Constraints can be defined either in column level or in table level

True False
Unique constraints means:

Columns cannot have NULL values Columns values should be different

Primary Key Constraint


Add a simple primary key constraint
 Column level: when creating the table

CREATE TABLE table_name (

column1 data_type(size) CONSTRAINT <constraint_name> PRIMARY


KEY,

column2 data_type(size),.....,

column3 data_type(size)

);

 Table level

Alter Table table_name ADD CONSTRAINT <constraint_name> PRIMARY


KEY(column_name);
Add a simple primary key constraint
Example
Alter Table Student ADD CONSTRAINT pk_student PRIMARY KEY(student_id);

Add a composed primary key


constraint
 Solution 1: when creating the table

CREATE TABLE table_name (

column1 data_type(size),

column2 data_type(size),.....,

column3 data_type(size),

CONSTRAINT <constraint_name> PRIMARY KEY (column1,column2)

);

 Solution 2:

Alter Table table_name ADD CONSTRAINT <constraint_name> PRIMARY


KEY(column1,column2);

Drop a primary key constraint


 Syntax:

Drop CONSTRAINT constraint_name;

Assessment: Quiz
Which of the following SQL command is correct to add a primary key constraint to the
Product table on product_id column. We suppose that the table is already created
Product (Product_id, Product_name, Price)

Alter TABLE Product ADD CONSTRAINT pk_product PRIMARY KEY(product_id);


Alter Product ADD CONSTRAINT pk_product PRIMARY KEY(product_id); Alter TABLE
Product ADD PRIMARY KEY CONSTRAINT pk_product (product_id);

Foreign Key Constraint


Add a foreign key constraint
When creating the table
CREATE TABLE table_name (

column1 data_type(size),

column2 data_type(size),.....,

column3 data_type(size),

CONSTRAINT <constraint_name> FOREIGN KEY (column_name)


REFERENCES Table_name (column_name)

);

Add a foreign key constraint


After creating the table
Alter TABLE table_name ADD CONSTRAINT <constraint_name>

FOREIGN KEY (column_name) REFERENCES Table_name (column_name);

Assessment: Quiz
Which of the following SQL command is correct to create the table Order with the
necessary constraints: Order(Order_id, Order_date, #Product_id, Quantity) NB: The
Product table is already created (( https://i.imgur.com/u58uDHb.png ))

CREATE TABLE Orders ( Order_id NUMBER, Order_date DATE, Product_id NUMBER,


Quantity NUMBER, CONSTRAINT pk_Orders PRIMARY KEY (Order_id), CONSTRAINT
fk_Orders FOREIGN KEY (Product_id) REFERENCES Product(Product_id) ); CREATE
TABLE Orders ( Order_id NUMBER, Order_date DATE, Quantity NUMBER, CONSTRAINT
pk_Orders PRIMARY KEY (Order_id), CONSTRAINT fk_Orders FOREIGN KEY (Product_id)
REFERENCES Product(Product_id) ); CREATE TABLE Orders ( Order_id NUMBER,
Order_date DATE, Product_id NUMBER, Quantity NUMBER, CONSTRAINT pk_Orders
PRIMARY KEY (Order_id), CONSTRAINT fk_Orders FOREIGN KEY (Product_id) );

Not Null, Unique, Check Constraints


Add a Not Null constraint
When creating the table
CREATE TABLE table_name(

column1 data_type(size) CONSTRAINT <constraint_name> NOT NULL ,

,...,

);

After creating the table


ALTER TABLE table_name modify column_name data_type CONSTRAINT
<constraint_name> NOT NULL;

The NOT NULL constraint must be defined only at the column level.

Add a Unique constraint


When creating the table
CREATE TABLE table_name (

column1 data_type CONSTRAINT <constraint_name> UNIQUE ,

,...,

);

After creating the table


ALTER TABLE table_name ADD CONSTRAINT <constraint_name> UNIQUE
(column_name);

A UNIQUE constraint allows NULL values unless you define NOT


NULL constraints

Add a Check constraint


The CHECK constraint ensures that all the values in a column
satisfies certain conditions.
When creating the table
CREATE TABLE table_name(

column1 data_type CONSTRAINT <constraint_name> CHECK (condition)


,

,...,

);

After creating the table


ALTER TABLE table_name ADD CONSTRAINT <constraint_name> CHECK
(condition);

Assessment: Quiz
Choose the best alternative Not Null constraints are applied to:

Table level Column level


Unique constraints means:

Columns cannot have NULL values Columns values should be different


In Unique constraints:

Columns can have NULL values Columns cannot have NULL values

Update data structure


Add Column
Syntax
ALTER TABLE table_name ADD column1 column_type, column2 column_type;

Example
ALTER TABLE Student ADD Adress VARCHAR2(100);

Alter Column
Syntax
ALTER TABLE table_name MODIFY column1 column_type, column2 column_type;
Example
ALTER TABLE Student MODIFY Adress VARCHAR2(200);

Drop Column
Syntax
ALTER TABLE table_name DROP column1,column2;

Example
ALTER TABLE Student DROP Adress;

Assessment: Quiz
Which of the following instruction is correct to add a Column Discount (Number) to
Orders table.

ALTER TABLE Orders ADD Discount NUMBER;


ALTER TABLE Orders ADD Discount VARCHAR2(20);
ALTER TABLE Orders ADD COLUMN Discount NUMBER;

Conclusion
Recap
 The Data definition Language provides queries to create data structure,
modify and drop data columns.
 There are Different types of constraints :
o Primary and Foreign Key
o Not Null, Unique and Check

Data Manipulation language (DML)

Data Manipulation language Introduction


Introduction
At the end of this Chapter, the learner will be able to use the DML (Data
Manipulation Language) to :

 Insert Data into table


 Update Data
 Delete data from table

Add data
Insert into clause
Implicit Insert: Insert in all table columns
INSERT INTO table_name VALUES

value_column1,

value_column2,

...,

value_columnn

);

The number of column values must be equal to the number of table


columns and of the same types

Insert into clause


Explicit Insert: Insert in a specified list of columns
INSERT INTO table_name

column1,

column2,

column3

VALUES

value_column1,

value_column2,

value_column3

);
Insert into Clause
 The values to be added must verify the defined constraints on the columns
table.
 Any record which does not verify the constraints will be rejected.
 The columns created with NOT NULL constraint must have values.
 We can use the following syntax to insert data from table.

INSERT INTO table_name (column1,column2)

SELECT column1, column2 from table_name1;

Assessment: Quiz
Which of the following instructions is correct to insert the following values in these
tables Customers (CustCode, custName, custAdress, custTel) Orders (OrderCode,
OrderDate, #CustCode) (( https://i.imgur.com/E2SfXdO.png ))

https://i.imgur.com/3eyFDbO.png https://i.imgur.com/9SSaWyd.png
https://i.imgur.com/xuXkpKl.png

Modify data
Update clause
Syntax:
UPDATE table_name SET column_name=new_value

[WHERE (conditions)];

It is not possible to update several tables in the same query.


The new values must satisfy the columns constraints
When there is no conditions in the query, then all the table rows will be
updated with the same value.

Assessment: Quiz
Which of the following is correct to update the address of the customer CO1 to
‘Sousse’ and the date of the Order 101 to ‘22/10/2019’ Customers (CustCode,
custName, custAdress, custTel) Orders (OrderCode, OrderDate, #CustCode)
((( https://i.imgur.com/NDIDw22.png )))

https://i.imgur.com/7ENlLFe.png https://i.imgur.com/a3vI0zA.png
https://i.imgur.com/QDK7nlH.png
Delete data
Delete clause
Syntax:
DELETE FROM table_name [WHERE (conditions)];

When there is no conditions in the query, then all the table records will be
removed, which will be equivalent to run this command:
TRUNCATE FROM table_name;

Assessment: Quiz
Which of the following is correct to remove the client ‘C01’ from the customers table
Customers (CustCode, custName, custAdress, custTel)
https://i.imgur.com/OI31IUP.png

https://i.imgur.com/oK2FuW9.png https://i.imgur.com/y1rTAXi.png
https://i.imgur.com/vZV7Qv5.png

Conclusion
Recap
The Data Manipulation Language provides queries to add data into tables,
update data and delete data rows.
There main three queries are :

 Insert,
 Update,
 Delete

Lab_Phase : MERN APP

Create a MERN APP


In this workshop, we are going to learn how to create a MERN application from
scratch.

Conclusion
In this super skill, we have learned how to create a MERN application from
scratch.
The next phase is to learn how to design this application.
Lab_Phase : Programming design and
Methodology

Programming design
This super skill is a workshops where the instructor is going to present the way
to design a web application.
The objective is to learn how to design a web application and the methodology to
do so.
Conclusion
This super skill is a workshops where the instructor is going to present the way
to design a web application
The objective is to learn how to design a web application and the methodology to
do so.

Lab_Phase : Design your application


Design your own app

This super skill is a checkpoint where we are going to apply what we


learn in the previous super skill

 The objective :
o Design our first MERN application using the tool that we learned
earlier.
o Practice what we have learned in the previous workshop, to create
the design of our application.

Conclusion
This super skill is a checkpoint where we are going to apply what we
learn in the previous super skill

 The objective :
o The objective is to design our first MERN application using the tool
that we learned earlier
o practice what we have learned in the previous workshop, to create
the design of our application.

Lab_Phase : Development
SSH Keys
Using SSH over HTTPS
When you push or pull code from GitHub, it's essential that GitHub can
successfully authenticate you before letting you run these commands. This
means that every time you try to git push or git pull, GitHub will ask you
for your email and password, and if they are correct the command will
execute. Without authentication, GitHub would be chaos: anyone could
push whatever code they wanted to any repository at any time!

So, being able to authenticate people when they push or pull is critical. But
it also gets tedious pretty quickly. When you are pushing and pulling
frequently, typing your credentials each time is bit of a hassle. Thankfully,
if you use the SSH protocol and configure everything properly, you will be
able to authenticate without having to put your username and password
each time. To do this we need to create an SSH key locally, add it to
GitHub, and make sure we can authenticate successfully.

Creating an SSH Key


This can be a bit intimidating, but if you follow the steps carefully, you
should be able to get this to work. (If you get stuck, GitHub also
provides instructions on configuring SSH.)

1. Open up Terminal.
2. Anywhere in Terminal paste the following ssh-keygen -t rsa -b 4096
-C "PUT YOUR EMAIL HERE" and replace "PUT YOUR EMAIL HERE" with
the email you used to sign up with GitHub.
3. Once you are prompted with Enter a file in which to save the
key (/Users/you/.ssh/id_rsa): [Press enter] press enter.
4. You will then be prompted to enter a passphrase. Just press enter here
5. You will then be prompted to enter a passphrase again. Just press enter
here as well
6. Paste the following in terminal: eval "$(ssh-agent -s)". If you do not
see a pid number, start from the first step again.
7. Paste the following in terminal: ssh-add ~/.ssh/id_rsa. if you see an
error message, start from the first step again.
8. Paste the following in terminal pbcopy < ~/.ssh/id_rsa.pub.
9. Head over to your GitHub account (make sure you sign in).
10.In the top right corner of any page, click your profile photo, then click
Settings.
11.In the user settings sidebar, click SSH and GPG keys.
12.Click New SSH key or Add SSH key.
13.In the "Title" field, add a descriptive label for the new key. For example, if
you're using a personal Mac, you might call this key "Personal MacBook
Air".
14.Paste your key into the "Key" field. (you can just right click and click paste
or use a keyboard shortcut. The previous command pbcopy did the
copying for you).
15.Click Add SSH key.
16.If prompted, confirm your GitHub password.
17.Anywhere in Terminal, type ssh -T [email protected] and if you see
"Successfully authenticated" (ignore the rest of the message) you are good
to go! If you do not see that, start from the beginning again.

This might seem like a pain, but thankfully you only need to do it once.
Once the connection is established, you'll be able to push and pull without
having to authenticate every single time.

Checkout and Reset


Introduction
As you get more comfortable adding and committing changes using git,
you may sometimes accidentally commit something you didn't mean to, or
you may want to remove some file that's in the working directory before
it's been staged. We'll show you some techniques to undo your changes in
this chapter. Please be warned that some of these commands are not
reversible, so use them with caution!

checkout
If you want to remove files from the working directory (before they have
been staged) you can use git checkout NAME_OF_FILE. Be careful with this -
you can not undo this command!

Here's a quick example. Create a new git repository, then add and commit
a blank file called first.txt. Once you've committed the file, echo hello >
first.txt to add some text to the file. If you check git status now, you'll
see that first.txt is not staged for commit. If you decide that you don't
like the change you just made to the file, you can type git checkout --
first.txt. If you cat first.txt you'll see the file is empty again!

clean
If you are dealing with an untracked or unmerged file, you cannot use git
checkout to remove it from the working directory. You must use git clean -
df to remove these files. Be careful with this - you can not undo this
command either! (Curious about the -df flags? Run man git-clean to learn
more about this command!)

git rm --cached
We've seen what to do if we have something in the working directory that
we want to remove. But what if we accidentally add something to the
staging area and want to move it back to the working directory? To do
this, you can type git rm --cached NAME_OF_FILE. If you need to remove a
folder pass the -r flag to git rm --cached. If you want to move all of your
files in the staging area to the working area you can type git rm -r --
cached .. If you want remove your files from the staging area AND the
working directory, you can type git reset --hard HEAD, but be careful - this
can not be undone!

Undoing commits with reset


We've seen how to remove things from the working directory, and how to
remove things from the staging area back into the working directory. But
sometimes we end up committing things we do not want to be
remembered. To undo commits we can use the git reset command. There
are 3 flags we can pass to this:

git reset --soft COMMIT_SHA - moves the files committed back to the
staging area

git reset --mixed COMMIT_SHA - moves the files committed back to the
working directory (if you use git reset without a flag, the default will be --
mixed)

git reset --hard COMMIT_SHA - undoes the entire commit (dangerous!!!)

What's the COMMIT_SHA, you ask? You may have noticed that every commit
has a unique identifier, called a sha, which identifies that commit. If you
type git log --oneline, you'll see your list of commit messages along with
the first seven characters of the commit sha. This is what you should pass
into each of these commands.

Using reset will not change the commit that you switch to but any commits
that have come after it.
So if we have 4 commits:
a808698 Fourth commit

ca0bbb4 Third commit

5ffcac5 Second commit

ac49968 First commit

And I want to move the last two commits to the staging area:
git reset --soft 5ffcac5, this will move whatever files we had in the Fourth
commit and Third commit back to the staging area.
Your Turn
1. Create a folder called destruction.
2. cd into that folder.
3. Initialize an empty git repository.
4. Create a file called done.txt.
5. Remove that file from the working directory (remember you can not
use git checkout).
6. Create a file called stage_me.txt.
7. Add stage_me.txt file to the staging area.
8. Move stage_me.txt file from the staging area to the working directory.
9. Add stage_me.txt file to the staging area.
10. Remove stage_me.txt from the staging area and the working
directory.
11. Create a new file called commit_me.txt.
12. Add commit_me.txt to the staging area.
13. Commit with the message "adding commit_me.txt".
14. Create another file called second.txt.
15. Add second.txt to the staging area.
16. Commit with the message "adding second.txt".
17. Check out your previous commits using git log --oneline to
see the unique identifier or SHA for each of your commits.
18. Using git reset, undo the previous commit and move your
changes back to the working directory.
19. Add second.txt again.
20. Commit with the message "Trying to commit again".
21. Using git reset undo the previous commit and move your
changes back to the staging area.
22. Commit with the message "Trying to commit again and again".
23. Using git reset undo the previous commit so that any changes
are not part of the working directory.
24. Pat yourself on the back! You just went through a pretty
complex git workflow!

Well done! Play around some more with these commands as they will be
essential when dealing with larger files, branches, and merges.

Branching
So far in our Git workflow we've only been working on a single branch. But
when you're working with a team, this isn't usually desirable. What if you
want to go off on your own and work on some experimental new feature?
It would be nice if you could do so without worrying about breaking the
code for everyone else, or conflicting with things that other people are
working on.
In most modern work flows, we do not do all of our work on a single
branch. Instead, we usually have many different branches for certain use
cases (bug fixes, new features, deployment), so it's essential to
understand how to create, delete, and merge branches.

Before creating a branch, let's first type git branch in the terminal. You
should see a list of all your branches; right now, there should just be a
single branch called master. This is the default branch for all Git
repositories.

To create a new branch we use the git checkout command with the -b flag
and then pass in a name of a branch. This looks like git checkout -b
NAME_OF_BRANCH.

If we want to move to another branch that has been previously created we


use the git checkout command and then specify the name of a branch.
This looks like git checkout NAME_OF_BRANCH

To delete a branch we make sure we are not on that branch and then
run git branch -D NAME_OF_BRANCH

To see all of the branches we have, we can type git branch -a. The -a flag
will include remote branches (branches on GitHub or other remote
locations). The flag does not matter right now, but it's good to get in the
habit of using it with the git branch command.

Try creating a branch called second branch. When you type git branch -a,
you should now see two branches; your current branch will have an
asterisk next to it. You can now add and commit files to the two branches
completely independently of one another! Try this out by adding separate
files to each branch.

Merging
With a branch workflow, we usually create a new branch for something we
are working on (a new feature, a redesign, etc.). When we are done with
that modification, we need to put our code back on the master branch.
Traditionally, the master branch is reserved for production code and
immediate bug fixes. In order to put our code back on the master branch
we need to merge our code in. Here's what that looks like:

Let's:

1. Create a folder called learn_branching and cd into it => mkdir


learn_branching && cd learn_branching.
2. Initialize a git repository => git init.
3. Create a file called first.txt => touch first.txt.
4. Add that file git add ..
5. Commit that file git commit -m "initial commit".
6. Create a new branch called feature => git checkout -b feature.
7. Now that you are on the feature branch, create a file called new.txt
=> touch new.txt.
8. Add that file => git add ..
9. Commit that file => git commit -m "adding new.txt".
10. Create another file called another.txt => touch another.txt.
11. Add that file => git add ..
12. Commit that file => git commit -m "adding another.txt".
13. Change back to the master branch => git checkout master.
Note that this branch has no awareness of new.txt or another.txt!
14. Merge our changes from the feature branch into
the master branch => git merge feature
15. Delete our branch called feature => git branch -D feature

Now if you take a look at git log --oneline --decorate you'll see that the
commit history on feature has ben merged into master! (--decorate gives
you nice coloring around branches and where they are in the commit
history.)

Your Turn
Practice makes perfect. Walk through the following steps to get more
experience with the branching and merging workflow.

1. Create a folder called branch_time.


2. cd into that folder.
3. Initialize an empty git repository.
4. Create a file called first.txt, then add and commit the file.
5. Create a new branch called amazing_feature.
6. Create a file called best.txt.
7. Add the file.
8. Commit the file with the message -m "added best.txt".
9. Switch back to the master branch.
10. Merge your changes from the feature branch into master.
11. Delete the feature branch.

Visual Diff Tools


Seeing commits and changes
Once you have made a commit, you can see the message, author and
some additional information using the git log command. When you type
this in you will also see the full SHA, which, as we've discussed, is a unique
identifier for the commit. To get out of git log you can type q.

As you work on a project by adding and modifying files and committing


changes, your commit history will expand and your git log will grow.
Sometimes you'll want to compare the history of your code at two different
points in time. To do this, we can use the git diff command.

If you want to see differences between your commits you can use the git
diff command and specify the SHA to compare. This will compare your
code now to your code at that SHA. Here are a few different kinds of diff-s
that you can see.

git diff - See changes in the working tree not yet staged for the next
commit.

git diff --cached - See Changes between the staging area and your last
commit.

git diff HEAD - See all changes in the working directory since your last
commit.

git diff ANOTHER_BRANCH - compare with the latest code on another branch

git diff HEAD~1 HEAD - compare with the previous commit (add ~2, ~3 for
older commits)

You can read more about git diff here

Try this out with one of your earlier examples, or create a repository from
scratch. Build up a commit history of five or so commits, then explore
these different ways to compare differences with git diff. It's best if you
modify files between commits rather than simply adding or removing files,
so that you can begin to appreciate git diff in its full glory!

Using a visual tool


Depending on your operating system, there are a few different visual tools
you can use, which give a much nicer interface to compare commits and
files than git diff. On OSX, opendiff is a wonderful place to start. If you
have XCode installed, you can type opendiff in the terminal and you should
not see an error. You can read more about it here, and here.

Merge Conflicts
Merging and Merge Conflicts
When we want to move changes from one branch to another, we use
the git merge command. Depending on the history of our commits, we can
merge two different ways:

1. Fast forward
2. Recursive
In the previous section, we saw a fast forward merge, which is when git
can easily tell when the commits happened and "put" one set of commits
on top of another chronologically.

When different commits happen at different times on two branches, and


git can not easily determine what order these commits happened in,
a recursive merge needs to happen. You don't need to know the details of
how the recursive strategy works; just know that it's an algorithm git uses
to try to merge branches when a simple fast-forward merge won't suffice.
(If you'd like to learn more, type man git-merge to check out the
documentation.)

Things get even worse when you commit changes to the same file on two
different branches. In that case, Git does not know which commit to go
with so it creates a merge conflict. This is basically Git's way of saying
"Hey human, you're asking me to put conflicting files in the commit
history; I don't know how to resolve these conflicts, so you take care of it
and let me know when you're done."

Let's see an example by creating our very own merge conflict! Starting in
our home directory:
mkdir merge_conflicts

cd merge_conflicts

git init

echo first > first.txt

git add .

git commit -m "first commit"

git checkout -b new_branch

echo second > second.txt

git add .

git commit -m "adding second.txt"

git checkout master

echo something_else > second.txt

git add .

git commit -m "adding second.txt on the master branch"


git merge new_branch

This final command should output


Auto-merging second.txt

CONFLICT (add/add): Merge conflict in second.txt

Recorded preimage for 'second.txt'

Automatic merge failed; fix conflicts and then commit the result.

Looks like we have an issue because when we tried to merge


the new_branch, git does not know which second.txt file to use! Both
branches have a file with the same name, but different contents.

If we take a look at our second.txt file (cat second.txt) we will see this
something_else

=======

second

>>>>>>> new_branch

What we see is the contents in HEAD, where master is, followed by the
contents in new_branch. Let's open up this file in our text editor and change
it so that it looks like this:
second

This is our way of letting Git know that we want to keep the text
from new_branch and discard the text from master.

Then let's go back to the terminal and run


git add .

git commit -m "fixing merge conflict"

From here you should be good to go.

Git is a great tool, but there are times when it won't know how to merge
things for you. The first time you see a merge conflict it can look a little
intimidating, but Git will put the two conflicting pieces of text right on top
of one another; the only thing you need to do is decide what text you want
to keep, delete the character separating the two options
(======= and >>>>>>>), and add and commit the results of your manual
merge.
Stashing
Sometimes you are working with certain files and do not want to add and
commit them, but you do not want to discard them either. For example,
maybe you're right in the middle of working on some feature when a huge
update gets pushed to your remote upstream, and you need to pull the
changes in right away to be sure that the code you're writing still works.

When you try to pull or merge code and you have changes in your working
directory, git won't let the pull or merge to go through. In other words, you
can't merge code into the branch you're working on unless your working
directory is clean. So, what should you do if you're working directory
isn't clean, but you aren't ready to commit yet? This is a perfect example
of where stashing can help. You can think of stashing as a temporary way
of remembering changes without making an official commit.

Here are the commands you can using when stashing:

git stash - stash your commits (same as git stash save)


git stash list - show the list of stashed changes
git stash apply - move the latest stashed change back into the working
directory, but keep it on the list
git stash pop - move the latest stashed change back into the working
directory and remove it from the list
git stash show - show the latest stash
git stash show stash@{number} - show a specific stashed change

You can also use git stash pop/apply stash@{number} to retrieve a specific
stashed change.

Stashing is quite useful when you are not ready to commit something, but
need a clean working directory. You can learn more about git
stash here and here.

Rebasing
Pre-reading
Before we dive deep into rebasing, start by reading this excellent tutorial
on Atlassian. Then answer the following questions:

 What does it mean when we say merging can "pollute" our commit history?
 How does rebasing solve the problem of not needing an extra commit?
 What is the "Golden Rule" of rebasing? Why is knowing this so important?

Rebasing Interactive Mode


Now that you have an idea of the key difference between rebase and merge,
let's take a look at how rebasing in interactive mode can give us complete
control over the entire commit history. You normally work in interactive
mode when cleaning up a commit history before merging onto master or
another production branch. Let's see what rebasing in interactive mode
looks like. If you are using VS Code, we highly recommend you add (or
already have) the following code (export EDITOR="code -w") to
your .bash_profile or .zshrc (if you are using zsh).

Let's start with a project, add a few commits and then explore the
command git rebase -i:
mkdir learn_rebase

cd learn_rebase

git init

echo first > first.txt

git add .

git commit -m "adding first"

echo second > second.txt

git add .

git commit -m "adding second"

echo third > third.txt

git add .

git commit -m "adding third"

echo fourth > fourth.txt

git add .

git commit -m "adding fourth"

echo fifth > fifth.txt

git add .
git commit -m "adding fifth"

echo sixth > sixth.txt

git add .

git commit -m "adding sixth"

git log --oneline | cat | wc -l # shows us we have 6 commits

git rebase -i HEAD~5 # let's rebase from the earliest commit possible

We should now see something that looks like this (don't worry if your SHAs
are different than this one)
pick 6f69a93 adding second

pick e2bb264 adding third

pick 9d46da5 adding fourth

pick dcce954 adding fifth

pick 5c040e4 adding sixth

# Rebase 77d05ef..5c040e4 onto 77d05ef (5 command(s))

# Commands:

# p, pick = use commit

# r, reword = use commit, but edit the commit message

# e, edit = use commit, but stop for amending

# s, squash = use commit, but meld into previous commit

# f, fixup = like "squash", but discard this commit's log message

# x, exec = run command (the rest of the line) using shell

# d, drop = remove commit

# These lines can be re-ordered; they are executed from top to bottom.

#
# If you remove a line here THAT COMMIT WILL BE LOST.

# However, if you remove everything, the rebase will be aborted.

# Note that empty commits are commented out

As we see above, we can do some pretty awesome things with these


commits. We can keep the commit, edit the commit message, edit the
commit (this will pause the rebasing and we can make changes to that
previous commit), squash or fixup the commit to turn a bunch of commits
into one, and even remove the commit if we want. Let's see what happens
if we change our rebase into this:
pick 6f69a93 adding second

squash e2bb264 adding third

squash 9d46da5 adding fourth

squash dcce954 adding fifth

squash 5c040e4 adding sixth

# Rebase 77d05ef..5c040e4 onto 77d05ef (5 command(s))

# Commands:

# p, pick = use commit

# r, reword = use commit, but edit the commit message

# e, edit = use commit, but stop for amending

# s, squash = use commit, but meld into previous commit

# f, fixup = like "squash", but discard this commit's log message

# x, exec = run command (the rest of the line) using shell

# d, drop = remove commit

# These lines can be re-ordered; they are executed from top to bottom.

# If you remove a line here THAT COMMIT WILL BE LOST.


#

# However, if you remove everything, the rebase will be aborted.

# Note that empty commits are commented out

If we save and close the file, we will see another file open up with the
following:
# This is a combination of 5 commits.

# The first commit's message is:

adding second

# This is the 2nd commit message:

adding third

# This is the 3rd commit message:

adding fourth

# This is the 4th commit message:

adding fifth

# This is the 5th commit message:

adding sixth

# Please enter the commit message for your changes. Lines starting

# with '#' will be ignored, and an empty message aborts the commit.

# Date: Thu Feb 27 11:12:39 2020 -0700


#

# interactive rebase in progress; onto efb5645

# Last commands done (5 commands done):

# squash 0e8059a adding fifth

# squash e3b524d adding sixth

# No commands remaining.

# You are currently editing a commit while rebasing branch 'master' on


'efb5645'.

# Changes to be committed:

# new file: fifth.txt

# new file: fourth.txt

# new file: second.txt

# new file: sixth.txt

# new file: third.txt

If you change the text on the line under "# The first commit's message is:"
and save and close the file, you will see only 2 commits now with a new
commit message! You have squashed a bunch of commits into one larger
one. This is very commonly done when working with other developers and
instead of having 10-15 small commits, you can squash them down to a
few larger ones for a cleaner and more accessible history.

Rebase with GitHub


Once you have rebased, if you try to push to GitHub, your push will be
rejected because the remote branch has a different commit history. In
order to bypass this, you can use the --force (or -f) flag after git push, but
be very careful - this will override your GitHub commit history.
You never want to do this if other people are working on that remote
branch. This is only useful if you are alone and want to push up your
commits before merging into a branch that others work on. You can learn
more about rebasing here.

Reverting
Revert
The git revert command undoes a commit, but unlike git reset, which
removes the commit from the commit history, it appends a new commit
with the resulting content. This prevents Git from losing history, which is
important for the integrity of your revision history and for reliable
collaboration. When you are working on a repository with other
developers, using git reset is highly dangerous because you alter the
history of commits which makes it very difficult to maintain a consistent
history of commits with other developers.

Let's imagine the following situation.

1. You are working on a file and you add and commit your changes
2. You then work on a few other things, and make some more commits
3. Now you realize, three or four commits ago, you did something that you
would like to undo - how can you do this?

You might be thinking, just use git reset, but this will remove all of the
commits after the one you would like to change - git revert to the rescue!
Let's walk through an example:
mkdir learn_revert # Create a folder called `learn_revert`

cd learn_revert # `cd` into the folder `learn_revert`

git init # Initialize a git repository

touch first.txt # Create a file called `first.txt`

echo Start >> first.txt # Add the text "Start" to `first.txt`

git add . # Add the `first.txt` file

git commit -m "adding first" # Commit with the message "Adding


first.txt"

echo WRONG > wrong.txt # Add the text "WRONG" to `wrong.txt`

git add . # Add the `wrong.txt` file

git commit -m "adding WRONG to wrong.txt" # Commit with the message


"Adding WRONG to wrong.txt"

echo More >> first.txt # Add the text "More" to `first.txt`

git add . # Add the `first.txt` file


git commit -m "adding More to first.txt" # Commit with the message
"Adding More to first.txt"

echo Even More >> first.txt # Add the text "Even More" to `first.txt`

git add . # Add the `first.txt` file

git commit -m "adding Even More to First.txt" # Commit with the message
"Adding More to first.txt"

# OH NO! We want to undo the commit with the text "WRONG" - let's
revert! Since this commit was 2 from where we are not we can use git
revert HEAD~2 (or we can use git log and find the SHA of that commit)

git revert HEAD~2 # this will put us in a text editor where we can
modify the commit message. If you are in vim you can press Shift + Z + Z
to save and close.

ls # wrong.txt is not there any more!

git log --oneline # note that the commit history hasn't been altered,
we've just added a new commit reflecting the removal of the `wrong.txt`

If you revert to a file that has been edited since the commit you want to
revert to, you will have a conflict that you will need to fix. You can read
more about git revert here.

Git reflog
Finally, if you make a change like undoing a commit using git reset, or
have reverted, or squashed and you want to undo that change, You can
type git reflog and you will see previous changes you have made with
unique SHAs. You can git reset --hard SHA to go back to a previous state.
To see this in action, try rebasing the example above to squash the last
two commits into one. Then take a look at the history you get back when
you type git reflog.

Conclusion
This super skill is a complimentary slides to the git and github super skill
also a workshop where we are going to see the development best
practices
 The objective :
o The objective is learn the best practices in web development, and
how to organize work when working with team

Lab_Phase : Develop your own


application

Development phase
This super skill is practice for all what we learn during the bootcamp

 The objective :
o The objective is to develop our own application, the one that we
have designed in the previous section

Conclusion
This super skill is practice for all what we learn during the bootcamp

 The objective :
o The objective is to develop our own application, the one that we
have designed in the previous section

Lab_Phase : Deployment

Deploy your project


This super skill is learn how to deploy an application in heroku

 The objective :
o The objective is to learn how deploy our application in a web host
and make it live.

Conclusion
This super skill is learn how to deploy an application in heroku
 The objective :
o The objective is to learn how deploy our application in a web host
and make it live.

Lab_phase :

Deployment Phase
This super skill is about deploying your application in heroku

 The objective :
o The objective is to deploy our application in a web host and make it
live.

Conclusion
This super skill is about deploying your application in heroku

 The objective :
o The objective is to deploy our application in a web host and make it
live.

Congratulation, by now you are ready to create your own


MERN application, also you are ready to learn any other
programming language. See you in a another track.

You might also like