Mysql
 sql >> Database >  >> RDS >> Mysql

Backup di database logici utilizzando MySQL Shell

Mysqldump è un popolare strumento di backup logico per MySQL, originariamente scritto da Igor Romanenko.

Mysqldump esegue backup logici (set di istruzioni SQL). Per impostazione predefinita, mysqldump non esegue il dump delle tabelle information_schema e non richiede mai performance_schema. Ma il principale svantaggio di mysqldump è che utilizza un solo thread durante il backup e il ripristino. (Anche il tuo server ha 64 core). Per superare questo inconveniente, MySQL ha introdotto nuove utilità sul client Shell. In questo blog spiegherò queste nuove utilità di backup.

Panoramica di MySQL Shell 

La shell MySQL è un client potente e avanzato e un editor di codice per il server MySQL. La shell MySQL 8.0.21 include alcune nuove interessanti utilità per creare un dump logico ed eseguire un ripristino logico per l'intera istanza del database, inclusi gli utenti.

La shell MySQL 8.0.22 includeva un backup logico di tabelle specifiche e il ripristino.

Utilità 

  • util.dumpInstance() - Esegui il dump di un'intera istanza del database, inclusi gli utenti
  • util.dumpSchemas() - Scarica una serie di schemi
  • util.loadDump() - Carica un dump in un database di destinazione
  • util.dumpTables() - Carica tabelle e viste specifiche.

util.dumpInstance()

L'utilità dumpInstance() eseguirà il dump di tutti i database presentati nella directory dei dati di MySQL. Escluderà gli schemi information_schema, mysql, ndbinfo, performance_schema e sys durante l'esecuzione del dump.

Sintassi 

util.dumpInstance(outputUrl[, options]) 

Verrà scaricato nel filesystem locale, outputUrl è una stringa che specifica il percorso di una directory locale in cui devono essere collocati i file di dump. È possibile specificare il percorso assoluto o un percorso relativo alla directory di lavoro corrente.

In questa utility, è disponibile un'opzione di prova per ispezionare gli schemi e visualizzare i problemi di compatibilità, quindi eseguire il dump con le opzioni di compatibilità appropriate applicate per rimuovere i problemi.

Opzioni 

Diamo un'occhiata ad alcune opzioni importanti per questa utility dump.

ocimds :[Vero | Falso]

Quando questa opzione è impostata su true, verificherà che il dizionario dei dati, il dizionario dell'indice e le opzioni di crittografia nelle istruzioni CREATE TABLE siano commentati nei file DDL, per garantire che tutte le tabelle si trovino nel MySQL data directory e utilizzare la crittografia dello schema predefinita.

E controllerà tutti i motori di archiviazione nelle istruzioni CREATE TABLE diversi da InnoDB, per la concessione di privilegi non idonei a utenti o ruoli e per altri problemi di compatibilità.

Se viene rilevata un'istruzione SQL non conforme, viene sollevata un'eccezione e il dump viene interrotto.

Quindi suggeriamo di utilizzare l'opzione dryRun per elencare tutti i problemi con gli elementi nel dump prima che venga avviato il processo di dumping. Usa l'opzione di compatibilità per risolvere automaticamente i problemi nell'output del dump.

Nota:questa opzione supporta solo l'utilità di dump dell'istanza e l'utilità di dump dello schema.

Esempio 1 

MySQL  localhost:3306 ssl  cart  JS > util.dumpInstance("/home/vagrant/production_backup", {ocimds: true,compatibility: ["strip_restricted_grants"]})

Acquiring global read lock

Global read lock acquired

All transactions have been started

Locking instance for backup

NOTE: Backup lock is not supported in MySQL 5.7 and DDL changes will not be blocked. The dump may fail with an error or not be completely consistent if schema changes are made while dumping.

Global read lock has been released

Checking for compatibility with MySQL Database Service 8.0.22

NOTE: MySQL Server 5.7 detected, please consider upgrading to 8.0 first. You can check for potential upgrade issues using util.checkForServerUpgrade().

NOTE: User 'backupuser'@'localhost' had restricted privileges (RELOAD, SUPER, CREATE TABLESPACE) removed

NOTE: User 'root'@'127.0.0.1' had restricted privileges (RELOAD, SHUTDOWN, FILE, SUPER, CREATE TABLESPACE) removed

NOTE: User 'root'@'::1' had restricted privileges (RELOAD, SHUTDOWN, FILE, SUPER, CREATE TABLESPACE) removed

NOTE: User 'root'@'localhost' had restricted privileges (RELOAD, SHUTDOWN, FILE, SUPER, CREATE TABLESPACE, PROXY) removed

ERROR: Table 'cart'.'sales' uses unsupported storage engine MyISAM (fix this with 'force_innodb' compatibility option)

Compatibility issues with MySQL Database Service 8.0.22 were found. Please use the 'compatibility' option to apply compatibility adaptations to the dumped DDL.

Util.dumpInstance: Compatibility issues were found (RuntimeError)

Quindi abbiamo una tabella myisam nel mio database del carrello. L'opzione dry run genera chiaramente l'errore.

Se vuoi correggere questi errori automaticamente nel tuo file dump, passa l'opzione di compatibilità come argomento nel tuo comando.

Esempio 2 

MySQL  localhost:3306 ssl  cart  JS > util.dumpInstance("/home/vagrant/production_backup", {dryRun: true ,ocimds: true,compatibility: ["strip_restricted_grants","force_innodb"]})

Acquiring global read lock

Global read lock acquired

All transactions have been started

Locking instance for backup

NOTE: Backup lock is not supported in MySQL 5.7 and DDL changes will not be blocked. The dump may fail with an error or not be completely consistent if schema changes are made while dumping.

Global read lock has been released

Checking for compatibility with MySQL Database Service 8.0.22

NOTE: MySQL Server 5.7 detected, please consider upgrading to 8.0 first. You can check for potential upgrade issues using util.checkForServerUpgrade().

NOTE: User 'backupuser'@'localhost' had restricted privileges (RELOAD, SUPER, CREATE TABLESPACE) removed

NOTE: User 'root'@'127.0.0.1' had restricted privileges (RELOAD, SHUTDOWN, FILE, SUPER, CREATE TABLESPACE) removed

NOTE: User 'root'@'::1' had restricted privileges (RELOAD, SHUTDOWN, FILE, SUPER, CREATE TABLESPACE) removed

NOTE: User 'root'@'localhost' had restricted privileges (RELOAD, SHUTDOWN, FILE, SUPER, CREATE TABLESPACE, PROXY) removed

NOTE: Table 'cart'.'sales' had unsupported engine MyISAM changed to InnoDB

Compatibility issues with MySQL Database Service 8.0.22 were found and repaired. Please review the changes made before loading them.

Writing global DDL files

Writing users DDL

Writing DDL for schema `cart`

Writing DDL for table `cart`.`salaries`

Writing DDL for table `cart`.`sales`

Writing DDL for table `cart`.`t1`

Preparing data dump for table `cart`.`salaries`

Data dump for table `cart`.`salaries` will be chunked using column `id`

Preparing data dump for table `cart`.`sales`

Data dump for table `cart`.`sales` will be chunked using column `id`

Preparing data dump for table `cart`.`t1`

NOTE: Could not select a column to be used as an index for table `cart`.`t1`. Chunking has been disabled for this table, data will be dumped to a single file.

Ora il ciclo di prova va bene e non ci sono eccezioni. Eseguiamo il comando dump dell'istanza per eseguire un backup dell'istanza.

La directory di destinazione deve essere vuota prima che avvenga l'esportazione. Se la directory non esiste ancora nella sua directory padre, l'utilità la crea.

Esempio 3 

MySQL  localhost:3306 ssl  cart  JS > util.dumpInstance("/home/vagrant/production_backup", {compatibility: ["strip_restricted_grants","force_innodb"],threads : 12})

Acquiring global read lock

Global read lock acquired

All transactions have been started

Locking instance for backup

Global read lock has been released

Writing global DDL files

Writing users DDL

Writing DDL for schema `cart`

Writing DDL for view `cart`.`price`

Writing DDL for table `cart`.`dummy`

Writing DDL for table `cart`.`salaries`

Writing DDL for schema `sbtest`

Writing DDL for table `sbtest`.`sbtest1`

Writing DDL for table `sbtest`.`sbtest10`

.

.

.

1 thds dumping - 99% (624.55K rows / ~625.40K rows), 896.15K rows/s, 10.13 MB/s uncompressed, 3.73 MB/s compressed 

Duration: 00:00:00s                                                                                               

Schemas dumped: 2                                                                                                 

Tables dumped: 18                                                                                                 

Uncompressed data size: 7.14 MB                                                                                   

Compressed data size: 2.79 MB                                                                                     

Compression ratio: 2.6                                                                                            

Rows written: 624550                                                                                              

Bytes written: 2.79 MB                                                                                            

Average uncompressed throughput: 7.14 MB/s                                                                        

Average compressed throughput: 2.79 MB/s

Sopra abbiamo usato un'opzione di compatibilità. Quindi, mentre esegue il dump, convertirà le tabelle myisam in innodb e le memorizzerà in un file.

Registri 

[[email protected] production_backup]$ cat [email protected]

-- MySQLShell dump 1.0.1  Distrib Ver 8.0.22 for Linux on x86_64 - for MySQL 8.0.22 (MySQL Community Server (GPL)), for Linux (x86_64)

--

-- Host: localhost    Database: cart    Table: sales

-- ------------------------------------------------------

-- Server version 5.7.32

--

-- Table structure for table `sales`

--

/*!40101 SET @saved_cs_client     = @@character_set_client */;

/*!50503 SET character_set_client = utf8mb4 */;

CREATE TABLE IF NOT EXISTS `sales` (

  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

  `name` varchar(30) DEFAULT NULL,

  `address` varchar(30) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

/*!40101 SET character_set_client = @saved_cs_client */;

Se stai usando mysqldump, memorizzerà l'output in un unico file. Ma qui genera più file come spiegheremo di seguito.

Questi sono i file disponibili nella directory di backup.

[[email protected] production_backup]$ ls -lrth

total 52K

-rw-r-----. 1 vagrant vagrant  707 Nov  6 02:36 @.json

-rw-r-----. 1 vagrant vagrant  287 Nov  6 02:36 cart.json

-rw-r-----. 1 vagrant vagrant  240 Nov  6 02:36 @.sql

-rw-r-----. 1 vagrant vagrant  240 Nov  6 02:36 @.post.sql

-rw-r-----. 1 vagrant vagrant 2.6K Nov  6 02:36 @.users.sql

-rw-r-----. 1 vagrant vagrant  733 Nov  6 02:36 [email protected]

-rw-r-----. 1 vagrant vagrant  486 Nov  6 02:36 cart.sql

-rw-r-----. 1 vagrant vagrant  575 Nov  6 02:36 [email protected]

-rw-r-----. 1 vagrant vagrant    8 Nov  6 02:36 [email protected]@0.tsv.zst.idx

-rw-r-----. 1 vagrant vagrant    8 Nov  6 02:36 [email protected]@@1.tsv.zst.idx

-rw-r-----. 1 vagrant vagrant   47 Nov  6 02:36 [email protected]@0.tsv.zst

-rw-r-----. 1 vagrant vagrant   24 Nov  6 02:36 [email protected]@@1.tsv.zst

-rw-r-----. 1 vagrant vagrant  252 Nov  6 02:36 @.done.json
  • Questo file @.json contiene i dettagli del server e l'elenco degli utenti, i nomi dei database e i loro set di caratteri.
  • Questo file cart.json contiene viste, SP, nomi di funzioni insieme all'elenco delle tabelle.
  • Questi file @.sql e @.post.sql contengono i dettagli della versione del server MySQL.
  • Questo file @.users.sql contiene un elenco di utenti del database.
  • Questo file [email protected] contiene la struttura della tabella.
  • Questo file cart.sql contiene un'istruzione del database.
  • Questo file [email protected] contiene nomi di colonne e set di caratteri.
  • Il file [email protected]@0.tsv.zst.idx è un file binario. Memorizza le statistiche degli indici delle tabelle.
  • Il file [email protected]@0.tsv.zst è un file binario e memorizza i dati.
  • Questo file @.done.json contiene l'ora di fine del backup e le dimensioni dei file di dati in KB.

util.dumpSchemas()

Eliminerà gli schemi specifici che hai menzionato negli argomenti per questa utilità.

Sintassi 

​util.dumpSchemas(schemas, outputUrl[, options])

Esempio 

MySQL  localhost:3306 ssl  cart  JS > util.dumpSchemas(["cart"], "/home/vagrant/production_backup",{compatibility: ["strip_restricted_grants","force_innodb"],threads :12})

Acquiring global read lock

Global read lock acquired

All transactions have been started

Locking instance for backup

NOTE: Backup lock is not supported in MySQL 5.7 and DDL changes will not be blocked. The dump may fail with an error or not be completely consistent if schema changes are made while dumping.

Global read lock has been released

Writing global DDL files

Writing DDL for table `cart`.`price_tag`

Writing DDL for schema `cart`

Writing DDL for table `cart`.`salaries`

Writing DDL for table `cart`.`sales`

NOTE: Table 'cart'.'sales' had unsupported engine MyISAM changed to InnoDB

Preparing data dump for table `cart`.`price_tag`

Data dump for table `cart`.`price_tag` will be chunked using column `id`

Data dump for table `cart`.`price_tag` will be written to 1 file

Preparing data dump for table `cart`.`salaries`

Data dump for table `cart`.`salaries` will be chunked using column `id`

Data dump for table `cart`.`salaries` will be written to 2 files

Preparing data dump for table `cart`.`sales`

Data dump for table `cart`.`sales` will be chunked using column `id`

Running data dump using 12 threads.

NOTE: Progress information uses estimated values and may not be accurate.

Data dump for table `cart`.`sales` will be written to 1 file                                               

1 thds dumping - 150% (3 rows / ~2 rows), 0.00 rows/s, 0.00 B/s uncompressed, 0.00 B/s compressed          

Duration: 00:00:00s                                                                              

Schemas dumped: 1                                                                                

Tables dumped: 3                                                                                 

Uncompressed data size: 53 bytes                                                                 

Compressed data size: 0 bytes                                                                    

Compression ratio: 53.0                                                                          

Rows written: 3                                                                                  

Bytes written: 0 bytes                                                                           

Average uncompressed throughput: 53.00 B/s                                                       

Average compressed throughput: 0.00 B/s                

util.dumpTables 

Se desideri eseguire il dump di tabelle specifiche, possiamo utilizzare l'utilità dumpTables.

Per i tavoli più grandi, mysqldump richiederà più tempo. Utilizzare l'utilità dumpTables per ridurre il tempo.

Sintassi 

util.dumpTables(schema, tables, outputUrl[, options])

Esempio 

util.dumpTables("sbtest", [ "sbtest14", "sbtest16" ], "/home/vagrant/specific_table",{dryRun: true})

​ MySQL  localhost:33060+ ssl  sbtest  JS > util.dumpTables("sbtest", [ "sbtest14", "sbtest16" ], "/home/vagrant/specific_table",{threads: 12})

Acquiring global read lock

Global read lock acquired

All transactions have been started

Locking instance for backup

Global read lock has been released

Writing global DDL files

Writing DDL for table `sbtest`.`sbtest16`

Writing DDL for table `sbtest`.`sbtest14`

Preparing data dump for table `sbtest`.`sbtest16`

Data dump for table `sbtest`.`sbtest16` will be chunked using column `id`

Preparing data dump for table `sbtest`.`sbtest14`

Data dump for table `sbtest`.`sbtest14` will be chunked using column `id`

Running data dump using 12 threads.

NOTE: Progress information uses estimated values and may not be accurate.

Data dump for table `sbtest`.`sbtest16` will be written to 1 file

Data dump for table `sbtest`.`sbtest14` will be written to 1 file

1 thds dumping - 99% (78.07K rows / ~78.08K rows), 0.00 rows/s, 0.00 B/s uncompressed, 0.00 B/s compressed

Duration: 00:00:00s                                                                                       

Schemas dumped: 1                                                                                         

Tables dumped: 2                                                                                          

Uncompressed data size: 892.39 KB                                                                         

Compressed data size: 348.91 KB                                                                           

Compression ratio: 2.6                                                                                    

Rows written: 78068                                                                                       

Bytes written: 348.91 KB                                                                                  

Average uncompressed throughput: 892.39 KB/s                                                              

Average compressed throughput: 348.91 KB/s 

Utilità di caricamento dump 

L'utilità di caricamento del dump fornisce lo streaming dei dati nell'archiviazione remota, il caricamento parallelo di tabelle o blocchi di tabelle, il monitoraggio dello stato di avanzamento, la capacità di ripristino e ripristino e l'opzione di caricamento simultaneo mentre il dump è ancora in corso.

Nota:l'utilità di caricamento del dump utilizza l'istruzione LOAD DATA LOCAL INFILE, quindi è necessario abilitare questo parametro local_infile a livello globale durante l'importazione.

L'utilità di caricamento dump verifica se la variabile di sistema sql_require_primary_key è impostata su ON e, in caso affermativo, restituisce un errore se nei file dump è presente una tabella senza chiave primaria.

Sintassi 

util.loadDump(url[, options])

Esempio 

MySQL  localhost:3306 ssl  sbtest  JS > util.loadDump("/home/vagrant/specific_table", {progressFile :"/home/vagrant/specific_table/log.json",threads :12})

Loading DDL and Data from '/home/vagrant/specific_table' using 12 threads.

Opening dump...

Target is MySQL 8.0.22. Dump was produced from MySQL 8.0.22

Checking for pre-existing objects...

Executing common preamble SQL

[Worker006] Executing DDL script for `sbtest`.`sbtest1`

[Worker004] Executing DDL script for `sbtest`.`sbtest12`

2 thds loading \ 100% (892.39 KB / 892.39 KB), 0.00 B/s, 0 / 2 tables done[Worker001] [email protected]@@0.tsv.zst: Records: 39034  Deleted: 0  Skipped: 0  Warnings: 0

[Worker005] [email protected]@@0.tsv.zst: Records: 39034  Deleted: 0  Skipped: 0  Warnings: 0

Executing common postamble SQL                                                                                                   

2 chunks (78.07K rows, 892.39 KB) for 2 tables in 1 schemas were loaded in 1 sec (avg throughput 892.39 KB/s)

0 warnings were reported during the load.

Per impostazione predefinita, gli indici fulltext per una tabella vengono creati solo dopo che la tabella è stata completamente caricata, il che velocizza l'importazione.

Puoi anche scegliere di disabilitare la creazione dell'indice durante l'importazione e creare gli indici in seguito.

L'utilità di caricamento dump importa su più thread per massimizzare il parallelismo. Se i file di dump sono stati compressi dalle utilità di dump di MySQL Shell, l'utilità di caricamento del dump gestisce la decompressione.

Puoi selezionare singole tabelle o schemi da importare o da escludere dall'importazione.

Puoi scegliere di saltare la registrazione binaria sull'istanza MySQL di destinazione durante il corso dell'importazione utilizzando un'istruzione SET sql_log_bin=0.

Conclusione

Questa è una delle potenti utility di MySQL 8.0. È ora possibile eseguire il dump da MySQL 5.6 e caricare questi dump in MySQL 5.7 o 8.0. Ma il dump degli account utente non è supportato quando si esegue il dump da MySQL 5.6. Nel mio prossimo blog confronteremo la velocità di backup/ripristino di MySQLdump e l'utilità della shell.