Files
mkdocs/docs/macos/webserver/mysql.md
2019-10-27 18:43:35 +01:00

622 lines
16 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# mysql
### Connexion à la base:
#### Se connecter à MySQL:
```bash
$ mysql -u root -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 18
Server version: 10.3.11-MariaDB Homebrew
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
```
#### Connexion à la base wordpress4 par lutilisateur root:
```bash
$ mysql -u root -D wordpress4 -p
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 17
Server version: 10.3.11-MariaDB Homebrew
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [wordpress4]>
```
#### Quitter MySQL:
```bash
MariaDB [wordpress4]> exit
Bye
```
### Types de bases (moteur de stockage):
[InnoDB](https://dev.mysql.com/doc/refman/5.5/en/innodb-storage-engine.html)
Conseil: enable innodb_file_per_table = 1 option to put indexes and data for individual tables into distinct files.
Requête pour trouver les tables InnoDB parmi toutes les bases:
```mysql
mysql> SELECT table_schema, table_name FROM INFORMATION_SCHEMA.TABLES WHERE engine = 'innodb';
```
Constitution de Mysql (par défaut):
```bash
bruno@silverbook:/usr/local/var/mysql$
-rw-r----- 1 bruno admin 15114 28 nov 08:08 ib_buffer_pool
-rw-rw---- 1 bruno admin 50331648 3 déc 10:35 ib_logfile0
-rw-rw---- 1 bruno admin 50331648 24 oct 12:51 ib_logfile1
-rw-rw---- 1 bruno admin 79691776 3 déc 10:35 ibdata1
-rw-rw---- 1 bruno admin 12582912 28 nov 16:53 ibtmp1
-rw-rw---- 1 bruno admin 1272770 3 déc 10:35 silverbook.home.err
-rw-rw---- 1 bruno admin 5 28 nov 16:53 silverbook.home.pid
```
- ibdata1: fichier de 10Mo extensible. InnoDB y stocke tout (bases,tables, index...) pour éviter la fragmentation.
- ib_logfile0, ib_logfile1: 2 fichiers log de 5Mo.
- ibtmp1
- ib_buffer_pool:
- silverbook.home.err: fichier log des erreurs
http://forum.wgpower.net/technique/innodb-fichier-ibdata1-trop-37009_1.html
https://vdachev.net/2007/02/22/mysql-reducing-ibdata1/
https://stackoverflow.com/questions/3456159/how-to-shrink-purge-ibdata1-file-in-mysql
[MyISAM](https://dev.mysql.com/doc/refman/5.5/en/myisam-storage-engine.html)
#### Connaitre le type de bases par défaut:
<u>mysql> show engine;</u>
```bash
MariaDB [(none)]> show engines;
+--------------------+---------+----------------------------------------------------------------------------------+--------------+------+------------+
| Engine | Support | Comment | Transactions | XA | Savepoints |
+--------------------+---------+----------------------------------------------------------------------------------+--------------+------+------------+
| MRG_MyISAM | YES | Collection of identical MyISAM tables | NO | NO | NO |
| CSV | YES | Stores tables as CSV files | NO | NO | NO |
| MEMORY | YES | Hash based, stored in memory, useful for temporary tables | NO | NO | NO |
| MyISAM | YES | Non-transactional engine with good performance and small data footprint | NO | NO | NO |
| Aria | YES | Crash-safe tables with MyISAM heritage | NO | NO | NO |
| InnoDB | DEFAULT | Supports transactions, row-level locking, foreign keys and encryption for tables | YES | YES | YES |
| PERFORMANCE_SCHEMA | YES | Performance Schema | NO | NO | NO |
| SEQUENCE | YES | Generated tables filled with sequential values | YES | NO | YES |
+--------------------+---------+----------------------------------------------------------------------------------+--------------+------+------------+
8 rows in set (0.007 sec)
```
#### ENGINE utilisé pour une table:
<u>mysql> SELECT TABLE_NAME, ENGINE FROM information_schema.TABLES where TABLE_SCHEMA = 'database';</u>
```bash
MariaDB [(none)]> SELECT TABLE_NAME, ENGINE FROM information_schema.TABLES where TABLE_SCHEMA = 'zenphoto';
+------------------+--------+
| TABLE_NAME | ENGINE |
+------------------+--------+
| _menu | InnoDB |
| .tags | InnoDB |
| .plugin_storage | InnoDB |
| _images | InnoDB |
| .pages | MyISAM |
| .menu | InnoDB |
| _plugin_storage | InnoDB |
| .admin_to_object | InnoDB |
| _tags | InnoDB |
.../...
| .captcha | InnoDB |
| .news | InnoDB |
| .comments | MyISAM |
| _admin_to_object | InnoDB |
| _comments | InnoDB |
| _pages | InnoDB |
+------------------+--------+
32 rows in set (0.012 sec)
```
### Bases:
#### Voir toutes les bases:
<u>mysql> SHOW DATABASES;</u>
```bash
MariaDB [(none)]> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| funnymac |
| ghost_prod |
| information_schema |
| mgpt |
| mysql |
| performance_schema |
| phpmyadmin |
| piwik |
| python |
| ssi |
| wordpress4 |
| wordpress5 |
| xhprof |
| xhprof_gui |
| yeswiki |
| zenphoto |
+--------------------+
16 rows in set (0.007 sec)
```
#### Utiliser une base existante:
<u>mysql> USE database;</u>
```bash
MariaDB [(none)]> USE ssi
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MariaDB [ssi]>
```
#### Supprimer une base:
<u>mysql> DROP DATABASE database</u>
```bash
MariaDB [(none)]> DROP DATABASE zenphoto
```
### Tables:
#### Voir les tables de la base courante:
<u>mysql [database]> SHOW TABLES;</u>
```bash
MariaDB [zenphoto]> SHOW TABLES;
+--------------------+
| Tables_in_zenphoto |
+--------------------+
| .admin_to_object |
| .administrators |
| .albums |
| .captcha |
| .comments |
| .images |
.../...
| _news |
| _news2cat |
| _news_categories |
| _obj_to_tag |
| _options |
| _pages |
| _plugin_storage |
| _search_cache |
| _tags |
+--------------------+
32 rows in set (0.000 sec)
```
#### Structure dune table:
<u>mysql [database]> DESCRIBE table;</u>
```bash
MariaDB [zenphoto]> DESCRIBE _tags;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | UNI | NULL | |
+-------+------------------+------+-----+---------+----------------+
2 rows in set (0.030 sec)
```
#### Renommer une table:
mysql [database]> ALTER TABLE table AS new_table;
```bash
MariaDB [zenphoto]> ALTER TABLE _tags RENAME AS _new-tags;
```
#### Vérification des tables :
<u>2 solutions:</u>
**1) CHECK TABLE table;**
```bash
MariaDB [zenphoto]> CHECK TABLE _tags;
+----------------+-------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+----------------+-------+----------+----------+
| zenphoto._tags | check | status | OK |
+----------------+-------+----------+----------+
1 row in set (0.043 sec)
```
**2) [mysqlcheck](https://mariadb.com/kb/en/library/mysqlcheck/)**
mysqlcheck verrouille chaque table en lecture seule (la base est alors inaccessible pour les autres processus pendant ce temps) pour vérification ou réparation.
```bash
$ mysqlcheck -u root -ppassword zenphoto
zenphoto..admin_to_object OK
zenphoto..administrators OK
zenphoto..albums OK
zenphoto..captcha OK
zenphoto..comments OK
zenphoto..images OK
zenphoto..menu OK
.../...
zenphoto._news2cat OK
zenphoto._news_categories OK
zenphoto._obj_to_tag OK
zenphoto._options OK
zenphoto._pages OK
zenphoto._plugin_storage OK
zenphoto._search_cache OK
zenphoto._tags OK
```
#### Optimiser:
Les bases InnoDB ne supportent pas loption OPTIMIZE.
A la place,MySQL crée une nouvelle table, y copie toutes les lignes, efface lancienne table, renomme la nouvelle et lance ANALYSE
```bash
mysqlcheck -u root -ppassword -o --all-databases
funnymac.download OK
funnymac.downloads OK
funnymac.eggs OK
funnymac.ipod OK
funnymac.ipod_news OK
funnymac.ipod_vers OK
funnymac.liens OK
funnymac.livre OK
funnymac.note OK
funnymac.numeric_info Table is already up to date
funnymac.numeric_log OK
funnymac.numeric_vers OK
funnymac.tips OK
funnymac.truc OK
funnymac.vote OK
ghost_prod.accesstokens
note : Table does not support optimize, doing recreate + analyze instead
status : OK
```
#### Réparer des tables :
[MySQL Server logs](https://dev.mysql.com/doc/refman/5.7/en/server-logs.html)
La 1ere chose à faire en cas de problèmes est de consulter les fichiers logs. Ceux-çi sont généralement avec les tables:
```bash
#osx (Homebrew):
$ cd /usr/local/var/mysql
total 388560
drwxr-xr-x 32 bruno admin 1024 28 nov 16:53 .
drwxrwxr-x 13 bruno admin 416 16 fév 2018 ..
-rw-rw---- 1 bruno admin 16384 28 nov 08:08 aria_log.00000001
-rw-rw---- 1 bruno admin 52 28 nov 08:08 aria_log_control
drwx------ 48 bruno admin 1536 1 déc 17:05 funnymac
drwx------ 53 bruno admin 1696 1 déc 17:05 ghost_prod
-rw-r----- 1 bruno admin 15114 28 nov 08:08 ib_buffer_pool
-rw-rw---- 1 bruno admin 50331648 3 déc 07:19 ib_logfile0
-rw-rw---- 1 bruno admin 50331648 24 oct 12:51 ib_logfile1
-rw-rw---- 1 bruno admin 79691776 3 déc 07:19 ibdata1
-rw-rw---- 1 bruno admin 12582912 28 nov 16:53 ibtmp1
drwx------ 9 bruno admin 288 1 déc 17:05 mgpt
-rw-rw---- 1 bruno admin 0 24 jul 2017 multi-master.info
drwx------ 89 bruno admin 2848 1 déc 17:05 mysql
drwx------ 3 bruno admin 96 24 jul 2017 performance_schema
drwx------ 41 bruno admin 1312 1 déc 17:05 phpmyadmi
-rw-rw---- 1 bruno admin 1271878 3 déc 07:19 silverbook.home.err
-rw-rw---- 1 bruno admin 5 28 nov 16:53 silverbook.home.pid
```
<u>Pour réparer, 2 solutions:</u>
**1) REPAIR TABLE:**
- ne nécessite pas larrêt de MySQL
- uniquement base MyISAM
```bash
MariaDB [zenphoto]> REPAIR TABLE _tags;
+----------------+--------+----------+---------------------------------------------------------+
| Table | Op | Msg_type | Msg_text |
+----------------+--------+----------+---------------------------------------------------------+
| zenphoto._tags | repair | note | The storage engine for the table doesn't support repair |
+----------------+--------+----------+---------------------------------------------------------+
1 row in set (0.006 sec)
```
Si lerreur persiste, **vider le cache** (Flush all cache)
**2) mysqlcheck -r:**
- nécessite un arrêt du service MySQL
- uniquement base MyISAM
[MyISAM](https://dev.mysql.com/doc/refman/5.5/en/myisam-storage-engine.html):
```bash
$ mysqlcheck -u root -ppassword -r zenphoto .comments
zenphoto..comments OK
```
[InnoDB](https://dev.mysql.com/doc/refman/5.5/en/innodb-storage-engine.html):
```bash
$ mysqlcheck -u root -ppassword -r zenphoto _tags
zenphoto._tags
note : The storage engine for the table doesn't support repair
```
Pour les tables InnoDB, il faut [forcer la récupération](https://dev.mysql.com/doc/refman/5.5/en/forcing-innodb-recovery.html):
1) Arrêter **mysqld**:
2) Sauvegarder **mysql**:
```bash
#Linux
/var/lib/mysql/
#osx (Homebrew)
/usr/local/var/mysql/
```
3) Ajouter au fichier de configuration MySQL my.cnf:
```
#osx (Homebrew): /usr/local/etc/my.cnf
[mysqld]
innodb_force_recovery = 4
```
4) Redémarrer **mysqld**:
5a) Faire un dump des tables de la base avec **SELECT ... INTO OUTFILE**:
```mysql
MariaDB [zenphoto]> SELECT * FROM _tags INTO OUTFILE '/tmp/corrupted.txt';
Query OK, 170 rows affected (0.011 sec)
# Pour exporter au format csv:
MariaDB [zenphoto]> SELECT * FROM _tags INTO OUTFILE '/tmp/corrupted.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n';
Query OK, 170 rows affected (0.006 sec)
```
5b) Faire. un dump de toutes les tables:
```bash
$ mysqldump -A -u root -ppassword > '/tmp/dump.sql';
```
6) Parfois cela peut suffire. Sinon,
7) Supprimer les tables / bases corrompues (DROP ...)
8) Arrêter **mysqld**:
9) Supprimer les ib*:
```bash
#Linux
/var/lib/mysql/ib*
#osx (Homebrew)
/usr/local/var/mysql/ib*
```
10) Quitter le mode force recovery:
```
[mysqld]
#innodb_force_recovery = 0
```
11) Redémarrer **mysqld**:
12) Restaurer les bases:
```bash
$ mysql -u root -ppassword < dump.sql
```
https://www.nixpal.com/mysql-innodb-corruption-repair-guide/
#### Vérifier et réparer:
Vérifier toutes les bases et réparer les tables corrompues:
```bash
$ mysqlcheck -u root -p -A --auto-repair
Enter password:
funnymac.download OK
funnymac.downloads OK
…/…
```
#### Erreur de syntaxe:
Les commandes doivent se terminer par un **;**
```bash
MariaDB [(none)]> mysqlcheck zenphoto
->
-> \c
MariaDB [(none)]>
```
Sinon taper **\c** pour revenir.
#### Tache CRON pour maintenance MySQL
```bash
echo "0 4 * * Sun root mysqlcheck -u maintenance --optimize --all-databases" > /etc/cron.d/mysqlcheck
```
```bash
$ mysql_upgrade -u root -ppassword
Phase 1/7: Checking and upgrading mysql database
Processing databases
mysql
mysql.column_stats OK
mysql.columns_priv OK
mysql.db OK
mysql.event OK
```
#### BASH : exécuter une requête MySql et exploiter le résultat
```bash
$ echo "SHOW DATABASES;" | mysql -h localhost -u root -ppassword
Database
information_schema
mysql
performance_schema
wordpress
zenphoto
```
[exécuter une requête MySql et exploiter le résultat](https://www.quennec.fr/trucs-astuces/systèmes/gnulinux/utilisation/bash-exécuter-une-requête-mysql-et-exploiter-le-résultat)
#### Créer un utilisateur avec les permissions lecture seule pour le backup des bases.
```mysql
GRANT SELECT, LOCK TABLES ON *.* TO 'MYBACKUPUSER'@'%' IDENTIFIED BY 'MYPASSWORD';
```