Monday, September 24, 2012

REPLICATION


Replication

Replication is a way to configure a MySQL database to update on a remote server whenever the local client is updated.
Replication allows you to take one database, make an exact copy of it on another server, and set one of them (the slave) to take all its updates from the other (the master).

¨  Replication is the frequent electronic copying data from a database in one computer or server  to a database in another so that all users share the same level of information.
¨  Replication allows you to take one database, make an exact copy of it on another server, and set one of them (the slave) to take all its updates from the other (the master).

First in your my.ini file search for this line
#skip-networking
#bind-address = 127.0.0.1
Uncomment out these lines (remove the “#” character). If these lines do not exist, add them. 

Setting up Replication
Configuring Master:
¨  In your my.ini file put these lines:
            [mysqld]
            log-bin = allen_binary
            binlog-do-db=exampledb    
            server-id=1 
log-bin indicates that the master will use binary update logging, binlog-do-db indicates which database we will use and server-id is a unique number to differentiate each of the master and slave machines. By convention, the master is usually set to 1, and the slaves from 2 upward:

¨  Now in the mysql shell, we will grant a permission to a slave to replicate. The slave user will be replication_user, with a password of replication_pwd:
•      GRANT REPLICATION SLAVE ON *.* TO replication_user IDENTIFIED BY 'replication_pwd';
•      GRANT RELOAD ON *.* TO replication_user IDENTIFIED BY 'replication_pwd';
•      GRANT SUPER ON *.* TO replication_user IDENTIFIED BY 'replication_pwd';


¨  You can also type this
>FLUSH privileges
Once you have given the desired privileges for your user, you will need to FLUSH privileges in order to complete the setup and to make the new settings work.
¨  Then use the database you want to replicate
>use replicationdb;
¨  master-host = 192.168.4.100
¨  master-user = replication_user
¨  master_password = replication_pwd
¨  server-id = 3
¨  master-connect-retry=60
¨  replicate-do-db = replication_db

There are two possibilities to get existing tables and data from replicationdb from master to slave
¨  make a database dump
mysqldump -u root -proot  -- opt replicationdb > C:replicationdb.sql
Transfer this file to your slave server
¨   load data from master
If you want to go the LOAD DATA FROM MASTER; 
way then there is nothing you must do right now.

¨  Finally we have to unlock the tables in replicationdb:
¨  mysql -u root -p
Enter password:
UNLOCK TABLES;
quit;
¨  Now the configuration on the master is finished. On to the slave...

¨  Now we will configure the slave:
¨  First create database replicationdb then quit mysql by “quit” command
¨  In the my.ini or my.cfg file, put these lines
Replace the master-host setting with the actual IP address of the master server, Master-user is the user created on the master for replication as well as the master-password. The server_id can be any number, as long as it's not the same as the server_id on the master: 

¨  Then quit and copy the sql
¨  Then on the mysql shell copy the replicationdb data from the master to the slave
>mysql -u root replicationdb < C:replicationdb.sql
¨  Then we restart MySQL

If you have not imported the master replicationdb with the help of an SQL dump, then lets use the LOAD DATA FROM MASTER;
>mysql -u root
>LOAD DATA FROM MASTER;
>quit;
*If you have phpMyAdmin installed on the slave you can now check if all tables/data from the master replicationdb is also available on the slave replicationdb.
¨  Next step is to stop the slave to finish up the Slave configuration.

mysql -u root -p
Enter password:
SLAVE STOP;
¨  replace the values appropriately:
>CHANGE MASTER TO MASTER_HOST='192.168.0.100', MASTER_USER=‘replication_user', MASTER_PASSWORD='replication_pwd', MASTER_LOG_FILE=‘allen_binary.000001', MASTER_LOG_POS=106;
¨  MASTER_HOST is the IP address or hostname of the master (in this example it is 192.168.0.100).
¨  MASTER_USER is the user we granted replication privileges on the master.
¨  MASTER_PASSWORD is the actual password gave to the user on the master.
¨  MASTER_LOG_FILE is the file MySQL gave, back when you ran SHOW MASTER STATUS; on the master.
¨  MASTER_LOG_POS is the position MySQL gave back when you also ran SHOW MASTER STATUS; on the master.

¨  Then start the slave.
>START SLAVE;
And now, be aware that if your master server has already been using binary logging, you'll need to reset the binary log with RESET MASTER so that the slave can start updating from the beginning of the first binary log. Now start the slave server and connect. Once you've connected, check the slave status to see if replication has begun properly:

Configuring Master and Slave Files

¨  Master Configuration File Options
¨  Slave Configuration File Options

Master Configuration File Options
log-bin=filename
¡  Activates binary logging. This option must be present on the master for replication to occur. To clear the log, run RESET MASTER, and do not forget to run RESET SLAVE on all slaves.
log-bin-index=filename
¡  Specifies the name of the binary log index file (which lists the binary log files in order, so the slave will always know the active one). The default is hostname.index

¨  sql-bin-update-same
¡  If set, setting SQL_LOG_BIN to either 1 or 0 will automatically set SQL_ LOG_UPDATE to the same value, and vice versa. SQL_LOG_UPDATE should not be needed any more, so this option is unlikely to be used.
¡  binlog-do-db=database_name
¡  Only logs updates to the binary log from the database_name database. All other databases are ignored.

¨  binlog-ignore-db= database_name
¡  Logs all updates to the binary log except from the database_name database. You can also set the database to ignore on the slave.

Slave Configuration File Options
master-host=host
¡  Specifies the hostname or IP address of the master to which to connect. Has to be set for replication to begin. Once replication has begun, the master.info data will determine this, and you'll need to use a CHANGE MASTER TO statement to change it.
master-user=username
¡  Specifies the username the slave will connect to the master with. The user should have REPLICATION SLAVE permission on the master.
master-password=password
¡  Specifies the password with which the slave will connect to the master.

¨  master-port=portnumber
¡  Specifies the port the master listens on (defaults to the value of MYSQL_ PORT, usually 3306).
¨  master-connect-retry= seconds
¡  If the connection between the master and slave goes down, MySQL will wait this many seconds before trying to reconnect (default 60).
¡  master-ssl
¡  Specifies that replication take place using Secure Sockets Layer (SSL).

¨  master-ssl-key=key_name
¡  If SSL is set to be used (the master-ssl option), this specifies the master SSL key filename.
master-ssl-cert= certificate_name
¡  If SSL is set to be used (the master-ssl option), this specifies the master SSL certificate name.
master-info-file=filename
¡  Specifies the master information file (default master.info in the data directory), which keeps track of the point in the binary logs that the slave is at in the replication process.

Slave and Master Commands on mysql

Slave Replication Commands
¨  start and stop the replication process, respectively.





TRIGGERS


SQL trigger is an SQL statements or a set of SQL statements which is stored to be activated or fired when an event associating with a database table occurs.

Trigger implementation in MySQL
While trigger is implemented in MySQL has all features in standard SQL but there are some restrictions you should be aware.

Some of the restrictions:
•      It is not allowed to create a trigger for views or temporary table.
•      It is not allowed to use transaction in a trigger.
•      Return statement is disallowed in a trigger.

•      Creating a trigger for a database table causes the query cache invalidated.
*Query cache allows you to store the result of query and corresponding select statement.
In the next time, when the same select statement comes to the database server, the database server will use the result which stored in the memory instead of parsing and executing the query again.

•      All trigger for a database table must have unique name.
*It is allowed that triggers for different tables having the same name but it is recommended that trigger should have unique name in a specific database. 

To create the trigger, you can use the following naming convention:
Syntax:
(BEFORE | AFTER)_tableName_(INSERT| UPDATE | DELETE)

MYSQL Stored Procedures


A stored procedure is a segment of declarative SQL code, which is stored in the database catalog. A stored procedure can be invoked by a program, a trigger or even another stored procedure.

Stored Procedures Advantages
•      Stored procedure increases performance of application.
•      Stored procedure reduces the traffic between application and database.
•      Stored procedure is reusable and transparent to any application which wants to use it.
•      Stored procedure is secured.

Stored Procedures Disadvantages
•      Stored procedures make the database server high load in both memory and processors.
•      Stored procedure only contains declarative SQL statements.
•      Stored procedure is difficult to debug.
•      Store procedure is not easy to write and maintain. 

DATABASE BACK-UPS


Backing up is having a copy of your database or file in a database.

Backing up by directly copying files
An easy way to back up the data is to copy the files. Unlike BACKUP, directly copying the files does not automatically lock the tables, so you need to lock the tables yourself to get a consistent picture. Alternatively, you can do a direct copy while the server is down. Once the tables have been locked, you should flush the tables to make sure any unwritten indexes are written to disk.


Using mysqldump and mysqlhotcopy
            mysqldump and mysqlhotcopy are two ways to create back-up in Mysql.

Use the mysqldump script to create a dump file, that is, a file containing the SQL statements necessary to re-create the database.

Command:
Mysqldump –u username –p password database_name > directory:\backup_name.sql

Example:
Mysqldump –u root companydb > d:\backup.sql


Use the mysqlhotcopy script to create a data file. These copies the data files for a particular database directly. Mysqlhotcopy is run only in Unix and NetWare

Command:
shell> mysqlhotcopy db_name [/path/to/new_directory]

The BACKUP and RESTORE commands
The BACKUP statement creates a copy of the definition and data files of a MyISAM table.

Command:
BACKUP TABLE table_name TO 'directory:\\';

Example:
BACKUP TABLE department TO 'd:\\';




The RESTORE statement restores the data.

Command:
RESTORE TABLE tablename FROM '/db_backup_path'

Example:
mysql> RESTORE TABLE sales FROM 'c:\\db_backups';


Using SELECT INTO to back up and LOAD DATA INFILE to restore

Using SELECT INTO statements create a text file that can be used to restore the data with the LOAD DATA command or the mysqlimport utility.

There are three types of SELECT INTO…
- select ….into OUTFILE
Writes a selected row to a file
Syntax:
SELECT … INTO OUTFILE ‘file_name’ from [table_name];
Example:

- select ….into DUMPFILE
writes a single row to a file
Syntax:
SELECT … INTO DUMPFILE ‘file_name’ from [table_name] limit 1;
Example:

- select ….into VAR_LIST
selects column values and into variables
Syntax:
SELECT [column_name] INTO [variable_name] from [table_name];
Example:



Backing up Innodb tables

Two way using mysqldump and copy the file
- To copy file shutdown MySQL server make sure no errors
- Copy all InnoDB data file (ibdata file and .ibd file) to safe place
- Copy all .frm file
- Copy all InnoDB log file
- Copy you’re my.cnf configuration


Replication as a means of backup
Replication, which backs up onto another machine, but also replicates data loss across machines if it's caused by SQL statements.