# MySQL

## Basic

* persist data : `/var/lib/mysql`

* `docker run -p -d 3306:3306 -v ./mysql-data:/var/lib/mysql mysql:latest`

* ```yml
  version: "3.8"
  services:
    mysql:
      image: mysql:5.7.31
      volumes:
        - data-volume:/var/lib/mysql
  volumes:
    data-volume:
  ```

* ```shell
  // stop service
  sudo /etc/init.d/mysql stop
  
  // copy to new location
  sudo cp -R -p /var/lib/mysql /newpath
  
  // update folder location
  sudo gedit /etc/mysql/my.cnf
  
  // start service
  sudo /etc/init.d/mysql restart
  ```

* 

## SSH Tunneling

* to connect to db via SSH tunnel

```shell
$ ssh -L [local port]:[database host]:[remote port] [username]@[remote host]

// example
$ ssh -L 3306:rr-zf81fzm6ija52q623.mysql.kualalumpur.rds.aliyuncs.com:3306 tenghieyik@172.22.4.252

$ ssh -L host.docker.internal:3306:rr-zf81fzm6ija52q623.mysql.kualalumpur.rds.aliyuncs.com:3306 tenghieyik@172.22.4.252
```

* dump

```mysql
sql> database_name < dump.sql

$ mysqldump db_name > backup.sql

// improve export speed
$ mysqldump --add-drop-table --add-locks --database db > db.sql

$ mysql --init-command="SET SESSION FOREIGN_KEY_CHECKS=0;SET UNIQUE_CHECKS=0;" -u root -p < Backup_Database.mysql

// from mysql
mysql> use your_db_name;

mysql> source /opt/file.sql;
```

## Other



```sql
mysql> CREATE USER 'razerpay'@'%' IDENTIFIED BY 'razerpay-singapore';
mysql> GRANT All PRIVILEGES ON *.* TO 'razerpay'@'%';
mysql> FLUSH PRIVILEGES;

mysql> SHOW GRANTS FOR 'razerpay'@'%';
mysql> REVOKE ALL PRIVILEGES ON *.* FROM 'razerpay'@'%';
mysql> DROP USER 'razerpay'@'%';

// apply this for mysql-8 if encountered PublicKeyRetrieval error
mysql> ALTER USER 'razerpay'@'%' IDENTIFIED WITH mysql_native_password BY 'razerpay-singapore';
```



* mysql shell tools

```sql
mysql> SHOW GLOBAL VARIABLES LIKE 'local_infile';
mysql> SET GLOBAL local_infile = 'ON';

shell-js> util.loadDump("/mnt/data/worlddump", {dryRun: true})
shell-js> util.loadDump("razerpay-schema-prod-MY.sql", {threads: 88, waitDumpTimeout: 1800})
```

## Performance Optimization

* improve query for huge dataset

* configuration `my-custom.cnf`

```cnf
[mysqld]
innodb_buffer_pool_size = 2G
```



* configuration for `docker-compose.yml`

```yml
version: '3.1'

services:

  db:
    image: mysql
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root
    volumes:
        - ./persistent_data:/var/lib/mysql
        - ./etc/conf.d:/etc/mysql/conf.d
```

