mysql-doc (1)
mysql-doc (1)
SYSTEM ARCHITECTURE:
Client Layer
Server Layer
Storage Layer
1] Client Layer
The client give request instruction to the server with the help of command prompt or through
GUI screen by using MySQL commands and expressions.
Some important services of Client Layer are:
(a) Connection Handling
◦ The connection established between the server and the client.
Once client gets connected to the server at that time client get its own thread for its
connection, with the help of this thread all the queries from client side will executed.
(b) Authentication
Authentication performed on server side when client is connected to the MySQL server.
Authentication is done with the help of user name and password.
(c) Security
After authentication when the client is successfully connected to server, the server will
check that a particular client has the privileges to issue in certain queries against MySQL server.
2] SERVER LAYER
Server layer is responsible for all the logical functionalities of RDBMS of MySQL When the
Client give request instructions to the Server and the server gives the output as soon as the instruction is
matched.
(b) Parser
Here the input is broken into number of tokens.
(c) Optimizer
Here the query is checked, i.e rearranging the tables scanned, choosing the right indexes
and other changes that are necessary.
3] STORAGE LAYER
This Storage Engine Layer of MySQL Architecture make it’s unique and most preferable for
developer’s. Due to this Layer MySQL layer is counted as the mostly used RDBMS and is widely used.
Different type of storage provided by MySQL are:
a) InnoDB
b) MyISAM
c) Memory
d) CSV
1. RPM installation
For this first we need to download the rpm package from the official website of MYSQL
Community Server
▪ wget https://downloads.mysql.com/archives/get/p/23/file/mysql-8.0.321.el9.x86_64.rpm
bundle.tar
This is in the .tar format so we need to first extract all the files and then install them,
For installing all the extracted files we use the foll command:
yum install *rpm
rpm -ivh --nodeps *rpm
After installing all the packages we need to check if mysql is installed properly or not and for
that we need to check in the var/lib directory
cd /var/lib/mysql
Then we need to check the status of mysql service is active or not using the foll command:
systemctl status mysqld.service
First we need to login using the default pass that will be in the mysqld.log file
Once login first we need to reset the password using the foll query:
ALTER USER ‘username’@’localhost’ IDENTIFIED BY ‘new_password’;
2] BINARY INSTALLATION
First we need to install the tar file from the website:
https://downloads.mysql.com/archives/community/
In Centos install the file using the wget command as follows:
wget https://downloads.mysql.com/archives/get/p/23/file/mysql-8.0.16-el7-
x86_64.tar
▪ After the installation is complete then untar the tar file using the foll command:
tar -xvf mysql-8.0.16-el7-x86_64.tar
▪ Then again extract the files with .tar.gz extension using the same command :
tar -xvf mysql-8.0.16-el7-x86_64.tar
tar -xvf mysql-router-8.0.16-el7-x86_64.tar.gz
tar -xvf mysql-test-8.0.16-el7-x86_64.tar.gz
datadir=/var/lib/mysql
sock=/var/lib/mysql/mysqld.sock
port=3300
log-error= var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
/root/mysql-8.0.16-el7-x86_64/bin//mysql_secure_installation -uroot -p
-S'/var/lib/mysql1/mysql.sock'
After the password is set then access the mysql using the foll command:
/home/asmita/mysql-8.0.16-el7-x86_64/bin/mysql -uroot -p'MySQL@123'
-S'/var/lib/mysql1/mysql.sock'
MONITORING
We need to check the foll:
os-uptime – uptime
db-uptime - \s
disk partition – df -h
memory – free
BACKUP
mysqldump ;
used for creating backups in Mysql databases.
Syntax;
mysqldump db_name > backup_file.sql
If we want to take the backup of all the databases we use the foll cmd:
mysqldump --all-databases > all_databases.sql
where,
--log-error
Append warnings and errors to named file
--verbose
provides detailed information about the backup process.
o --all-databases :
This option is used when we need to take the backup for all the databases present.
o --single-transaction:
consistent backup: the --single-transaction option ensures a consistent backup of
your database by wrapping the entire mysqldump operation in a single transaction. This
guarantees that the backup reflects a consistent state of your database at the time the
transaction started
o -R(--routines):
Include stored routines (procedures and functions) for the dumped databases in the output.
o –triggers
Include triggers for each dumped table in the output. This option is enabled by default;
disable it with --skip-triggers.
o --verbose
allows you to display additional information about the backup process as it is occurring.
o --log-error:
It is used to show Log warnings and errors by appending them to the named file.
(Disconnecting from the localhost)---- this should be the last line of the log file that will
be created which means that backup is successful.
o --databases:
Dump several databases. Normally, mysqldump treats the first name argument on the
command line as a database name and following names as table names. With this option,
it treats all name arguments as database names.
It is used to specify multiple databases that you want to include in the backup.
Syntax:
mysqldump -u username -p --databases database1 [database2 ...] > backup_file.sql
o --no-data:
It is used to exclude the data from the SQL dump generated by the mysqldump
command. This option is useful when you want to export only the structure (schema) of
the database objects (tables, views, procedures, functions, triggers) without including the
actual data records.
Syntax:
mysqldump -u username -p --no-data database_name > schema_backup.sql
o --no-create-info:
is used to exclude the creation statements of database objects (such as tables, views,
procedures, functions, triggers) from the SQL dump generated by the mysqldump
command. This option is useful when you want to export only the data from the database
without including the structure definitions.
Syntax:
mysqldump -u username -p --no-create-info database_name > data_backup.sql
Restoration
mysql -u username -p database_name < backup_file.sql -f
where,
-f forcefully
It means that while doing the restoration if any error occurs then it will not stop the
execution .
Backup and Pipe to Remote Server
Other method:
create table employee_25072024 like employee;
insert into employee_25072024 select * from employee;
USER CREATION
Eg:
Create user ‘newuser’@’localhost’ identified by ‘Root@123’
If you want the user to connect from any host (% wildcard), use:
create user ‘username’@’%’ identified by ‘password’
Once the user is created we will grant the specific privileges to that user using the foll query:
GRANT privileges ON * . * TO 'username'@'host' IDENTIFIED BY 'password' ;
where,
first * is for database name(all databases)
.
second * is for table name(all tables present)
eg:
grant select on asmita.details to 'newuser'@'%' ;
or
grant select,update,insert on asmita.details to 'newuser'@'%' ;
REVOKE:
Revoke ALL PRIVILEGES from a user on a database:
REVOKE ALL PRIVILEGES ON db_name.* FROM user_name@'localhost';
Eg:
Revoke all privileges on asmita.details from ‘newuser’@’%’;
Other method:
Grant select(col1,col2) on db_name.tab_name to ‘username’@’%’;
Eg:
grant select(country,cust_name) on asmita.customers to 'newuser'@'%';
allows a MySQL user not only to use specific privileges themselves but also to grant
those same privileges to other users.
MASTER-SLAVE REPLICATION
Relay logs store events received from the master server before they are executed on the slave
database. This temporary storage ensures that if the slave server crashes or restarts, it can resume
replication from where it left off without relying solely on the master server.
If the master becomes unavailable temporarily, the slave can continue to apply changes from the
relay logs until the master is back online.
Binary logs are generated on the master server and contain the original database changes. Relay
logs are generated on the slave server and contain a copy of these changes after they have been
received and processed for replication.
Relay Log Files: Similar to binary logs on the master server, relay logs are stored as files on the
slave server. They are named sequentially, typically starting with relay-
bin.<sequence_number>.
Relay Log Index: MySQL maintains an index file (relay-log.info) that keeps track of the cur-
rent relay log file and position within that file.
bind-address=* in MySQL allows the server to listen for client connections on all available net-
work interfaces.
Replication setup:
For master-slave replication we need two servers one will be master and the other will be slave
where master has both R/W permissions whereas for slave it has only the R permission.
First check that server_id for both master and slave are different , if they are same then the
replication will not take place and we will need to change the server_id of master or slave.
We’ll also check that the binary logs are enabled or not;
Master server:
First we need to take a full backup of master server using the foll command:
Next we need to move that backup file on the secondary i.e. the slave server:
Master server;
On the master server create a new user and give grant permissions:
o Flush privileges;
Slave server:
o Check the replication server is properly working or not using the foll cmd:
o If the connection is working properly then execute the change master command as follows:
CHANGE MASTER TO
MASTER_HOST = '192.168.1.160',
MASTER_USER = 'test',
MASTER_PASSWORD = 'Test@123',
MASTER_LOG_FILE = ‘mysql-bin.000033’,
MASTER_LOG_POS = 197;
GTID REPLICATION:
gtid_mode=ON
enforce_gtid_consistency=ON
CHANGE MASTER TO
MASTER_HOST='192.168.1.160',
MASTER_PORT=3300,
MASTER_USER='test',
MASTER_PASSWORD='Test@123',
MASTER_AUTO_POSITION=1;
nano /etc/selinux/config
· InnoDB Buffer Pool focuses on enhancing the performance of the database by keeping frequently
accessed data in memory, reducing the need for disk reads and writes.
· Binary Log (Binlog) is crucial for replication, recovery, and auditing by recording all changes made
to the database.
Percona Backup:
xtrabackup --backup --datadir=/var/lib/mysql --target-dir=/home/Asmita
xtrabackup_binlog_info –
Basedir
Datadir
Logs
Socket
my.cnf
[mysqld]
Server-id
Basedir
Datadir
Log-error
Log-bin
socket
lower_case_table_names
It is a system variable that controls how MySQL handles table name case sensitivity on a case-
insensitive file system.
xtrabackup tool
Differential Backup: Backs up all changes made since the last full backup.
Incremental Backup: Backs up all changes made since the last backup, whether it was a full or in-
cremental backup.
Changing the ownership of the data directory is mandatory after the initialization of the data directory.
MYSQL UPGRADATION
SESSIONS IN PROCESSLIST:
To kill sleep sessions in MySQL, you can use the following commands:
```
KILL (SELECT id FROM information_schema.processlist WHERE command = 'sleep');
This command identifies the process IDs of sleeping sessions and immediately kills them.
```
SELECT CONCAT('KILL ', id, ';')
FROM information_schema.processlist
WHERE command = 'sleep'
INTO OUTFILE '/tmp/kill_sleep.sql';
SOURCE /tmp/kill_sleep.sql;
```
This method generates a SQL file with `KILL` commands for each sleeping session and then executes
the file.
Select now()
o Used to check the time zone in mysql
AUDIT LOGS
Once the slave is started then if the error occurs in 225 we need to check the table count on both the
master server(X.100) and 225
UPGRADATION
INDEXING
Collation defines how string data is compared, sorted, and ordered in the database, and is closely tied
to character sets, which define the set of characters that can be stored.
undo logs and redo logs are important mechanisms used for ensuring data integrity, supporting transac-
tion rollback and recovery, and maintaining the consistency of the database in case of failures
1. Undo logs:
a. Undo logs are used primarily for transaction rollback. They help to revert or "undo"
changes made by a transaction that has not been committed yet. This is important for
maintaining the ACID properties of the database, especially the Atomicity and Consis-
tency
-- Begin a transaction
START TRANSACTION;
-- Modify data
UPDATE employees SET salary = salary * 1.1 WHERE department = 'Sales';
The undo log, also known as the rollback segment, is a crucial part of the InnoDB storage engine. Its
primary purpose is to support transactional consistency and provide the ability to roll back changes
made during a transaction.
2. Redo Log:
The redo log, also known as the transaction log or InnoDB log, serves a different
purpose than the undo log. Its primary function is to ensure durability and aid in crash
recovery.
Redo Log not only records the changes made to the database but also includes the
modifications that are written into the rollback segments. In a database system, rollback
segments are used to temporarily store undo data during transactions. So, in addition to
tracking database changes, the Redo Log also captures the changes made to the rollback
segments. This ensures that during recovery procedures, the system can properly restore
the database to a consistent state by applying both the database changes and the
modifications stored in the rollback segments.
Write-ahead logging: The redo log follows a write-ahead logging approach, meaning
that changes are written to the redo log before the corresponding data pages are updated.
This ensures that in the event of a crash, the changes recorded in the redo log can be re-
played to restore the database to a consistent state.
Crash recovery: During crash recovery, the redo log is crucial for replaying the logged
changes to bring the database to a consistent state. By reapplying the changes recorded
in the redo log, InnoDB can recover transactions that were committed but not yet written
to disk.
-- Begin a transaction
START TRANSACTION;
-- Modify data
UPDATE products SET stock = stock - 10 WHERE id = 123;
Dirty Pages: These are pages in memory that have been modified but not yet written to disk.
InnoDB periodically flushes these pages to reduce the number of dirty pages in memory.
What is a Tablespace?
A tablespace in InnoDB is a logical container for storing data. InnoDB stores its data in a
variety of tablespaces, which can either be shared or dedicated to individual tables. The
tablespace contains one or more data files that store the actual content (data and indexes) of
the tables.
Types of tablespace:
1. System Tablespace (Shared Tablespace):
The system tablespace (usually the file ibdata1 by default) stores InnoDB's internal data,
such as metadata, undo logs, and doublewrite buffer.
All tables and indexes that do not use the file-per-table feature are stored here.
The system tablespace is a single large file that can grow over time as more data is added.
2. File-Per-Table Tablespaces:
In this model, each table (or its partitions) is stored in a separate tablespace file. Each table
has its own data file (e.g., .ibd file) for its table data and associated indexes.
This can improve performance because each table is stored independently, making it easier
to manage and optimize specific tables.
By enabling the innodb_file_per_table configuration option, MySQL stores each table in its
own .ibd file, rather than in the shared system tablespace.
INNODB ARCHITECTURE:
Durability:
innodb_flush_log_at_trx_commit = 1 ensures that the database is fully durable and can recover
committed transactions in case of a system crash. This is because the redo log is written to disk
and flushed on every commit.
innodb_flush_log_at_trx_commit = 0 or innodb_flush_log_at_trx_commit = 2 introduces the risk of los-
ing the last second’s worth of transactions if the system crashes before the log is flushed to disk.
innodb_flush_log_at_trx_commit = 0 is the fastest option, as it reduces the number of disk
flushes by writing the log to disk only once per second. This significantly improves throughput
and reduces I/O overhead.
innodb_flush_log_at_trx_commit = 1 introduces the most disk I/O, as it requires a disk flush on ev-
ery commit, which can reduce performance in systems with high transaction throughput.
innodb_flush_log_at_trx_commit = 2 offers a balance between performance and durability, as it
avoids frequent disk flushes but still provides some level of durability.
innodb_file_per_table: Determines whether InnoDB stores each table in its own tablespace file
or uses a shared tablespace.
InnoDB is a storage engine for MySQL that provides high-performance, reliability, and
ACID-compliant transactions. It is the default storage engine in MySQL and is commonly used for ap-
plications that require strong data integrity and support for complex transactions.
The InnoDB architecture has two main kinds of structures:
In-memory structures
on-disk structures
In-memory structure:
The in-memory structures are responsible for managing and optimizing the storage and retrieval of
data. The in-memory structures include:
Buffer pool
Change buffer
Adaptive hash index
Log buffer
1. Buffer pool:
a. The buffer pool is an area in main memory where InnoDB caches table and index data
as it is accessed.
b. The buffer pool permits frequently used data to be accessed directly from memory,
which speeds up processing. On dedicated servers, up to 80% of physical memory is
often assigned to the buffer pool.
2. Change buffer:
a. The change buffer is in charge of caching changes to the secondary index pages when
these pages are not in the buffer pool.
b. When we execute an INSERT, UPDATE, or DELETE statement, it changes the data of
the table and the secondary index pages. The change buffer caches these changes when
the relevant pages are not in the buffer pool to avoid time-consuming I/O operations.
3. Adaptive hash index:
a. An Adaptive Hash Index (AHI) is a feature in InnoDB (MySQL's default storage
engine) that optimizes certain types of queries by dynamically creating hash indexes in
memory, based on frequently accessed data. The adaptive part of this feature means that
InnoDB adjusts the hash index in response to query patterns, particularly for frequently
accessed index pages.
b. The goal of the Adaptive Hash Index (AHI) is to improve query performance, especially
for point lookups or queries that access a small set of rows based on specific key values.
4. Log Buffer
a. The log buffer is a memory area that holds the changes to be written to transaction logs.
b. The log buffer improves performance by writing logs to memory before periodically
flushing them to the redo log on disk.
c. The default size of the log buffer is often sufficient for most applications. But if you
have a write-intensive application, you can configure the log buffer size to enhance the
MySQL server performance.
On-disk structure:
InnoDB storage engine uses the on-disk structures to store data permanently on disks. These
structures ensure data integrity, offer efficient storage and support transactional features.
The on-disk structures include:
System tablespace
File-per-table tablespaces
General tablespaces
Undo tablespaces
Temporary tablespaces
Doublewrite buffer
o InnoDB uses the Doublewrite Buffer to store pages that have been flushed from the
buffer pool before their actual writing to InnoDB data files.s
o The Doublewrite Buffer allows InnoDB to retrieve a reliable page copy for recovery in
case a storage issue occurs.
Redo log
Undo logs
mysqlpump
It provides a faster and more efficient way of performing backups compared to mysqldump. It is specif-
ically designed to handle parallel backups of large databases, offering better performance, especially
when dealing with large datasets.