-
Notifications
You must be signed in to change notification settings - Fork 59
/
DB_Command.php
2037 lines (1845 loc) · 65.1 KB
/
DB_Command.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
use WP_CLI\Formatter;
use WP_CLI\Utils;
/**
* Performs basic database operations using credentials stored in wp-config.php.
*
* ## EXAMPLES
*
* # Create a new database.
* $ wp db create
* Success: Database created.
*
* # Drop an existing database.
* $ wp db drop --yes
* Success: Database dropped.
*
* # Reset the current database.
* $ wp db reset --yes
* Success: Database reset.
*
* # Execute a SQL query stored in a file.
* $ wp db query < debug.sql
*
* @when after_wp_config_load
*/
class DB_Command extends WP_CLI_Command {
/**
* Legacy UTF-8 encoding for MySQL.
*
* @var string
*/
const ENCODING_UTF8 = 'utf8';
/**
* Standards-compliant UTF-8 encoding for MySQL.
*
* @var string
*/
const ENCODING_UTF8MB4 = 'utf8mb4';
/**
* A list of incompatible SQL modes.
*
* Copied over from WordPress Core code.
* @see https://github.com/WordPress/wordpress-develop/blob/5.4.0/src/wp-includes/wp-db.php#L559-L572
*
* @var string[] Array of SQL mode names that are incompatible with WordPress.
*/
protected $sql_incompatible_modes = [
'NO_ZERO_DATE',
'ONLY_FULL_GROUP_BY',
'STRICT_TRANS_TABLES',
'STRICT_ALL_TABLES',
'TRADITIONAL',
'ANSI',
];
/**
* Creates a new database.
*
* Runs `CREATE_DATABASE` SQL statement using `DB_HOST`, `DB_NAME`,
* `DB_USER` and `DB_PASSWORD` database credentials specified in
* wp-config.php.
*
* ## OPTIONS
*
* [--dbuser=<value>]
* : Username to pass to mysql. Defaults to DB_USER.
*
* [--dbpass=<value>]
* : Password to pass to mysql. Defaults to DB_PASSWORD.
*
* [--defaults]
* : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
*
* ## EXAMPLES
*
* $ wp db create
* Success: Database created.
*/
public function create( $_, $assoc_args ) {
$this->run_query( self::get_create_query(), $assoc_args );
WP_CLI::success( 'Database created.' );
}
/**
* Deletes the existing database.
*
* Runs `DROP_DATABASE` SQL statement using `DB_HOST`, `DB_NAME`,
* `DB_USER` and `DB_PASSWORD` database credentials specified in
* wp-config.php.
*
* ## OPTIONS
*
* [--dbuser=<value>]
* : Username to pass to mysql. Defaults to DB_USER.
*
* [--dbpass=<value>]
* : Password to pass to mysql. Defaults to DB_PASSWORD.
*
* [--yes]
* : Answer yes to the confirmation message.
*
* [--defaults]
* : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
*
* ## EXAMPLES
*
* $ wp db drop --yes
* Success: Database dropped.
*/
public function drop( $_, $assoc_args ) {
WP_CLI::confirm( "Are you sure you want to drop the '" . DB_NAME . "' database?", $assoc_args );
$this->run_query( sprintf( 'DROP DATABASE `%s`', DB_NAME ), $assoc_args );
WP_CLI::success( 'Database dropped.' );
}
/**
* Removes all tables from the database.
*
* Runs `DROP_DATABASE` and `CREATE_DATABASE` SQL statements using
* `DB_HOST`, `DB_NAME`, `DB_USER` and `DB_PASSWORD` database credentials
* specified in wp-config.php.
*
* ## OPTIONS
*
* [--dbuser=<value>]
* : Username to pass to mysql. Defaults to DB_USER.
*
* [--dbpass=<value>]
* : Password to pass to mysql. Defaults to DB_PASSWORD.
*
* [--yes]
* : Answer yes to the confirmation message.
*
* [--defaults]
* : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
*
* ## EXAMPLES
*
* $ wp db reset --yes
* Success: Database reset.
*/
public function reset( $_, $assoc_args ) {
WP_CLI::confirm( "Are you sure you want to reset the '" . DB_NAME . "' database?", $assoc_args );
$this->run_query( sprintf( 'DROP DATABASE IF EXISTS `%s`', DB_NAME ), $assoc_args );
$this->run_query( self::get_create_query(), $assoc_args );
WP_CLI::success( 'Database reset.' );
}
/**
* Removes all tables with `$table_prefix` from the database.
*
* Runs `DROP_TABLE` for each table that has a `$table_prefix` as specified
* in wp-config.php.
*
* ## OPTIONS
*
* [--dbuser=<value>]
* : Username to pass to mysql. Defaults to DB_USER.
*
* [--dbpass=<value>]
* : Password to pass to mysql. Defaults to DB_PASSWORD.
*
* [--yes]
* : Answer yes to the confirmation message.
*
* [--defaults]
* : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
*
* ## EXAMPLES
*
* # Delete all tables that match the current site prefix.
* $ wp db clean --yes
* Success: Tables dropped.
*
* @when after_wp_load
*/
public function clean( $_, $assoc_args ) {
global $wpdb;
WP_CLI::confirm(
sprintf(
"Are you sure you want to drop all the tables on '%s' that use the current site's database prefix ('%s')?",
DB_NAME,
$wpdb->get_blog_prefix()
),
$assoc_args
);
$tables = Utils\wp_get_table_names(
[],
[ 'all-tables-with-prefix' => true ]
);
foreach ( $tables as $table ) {
$this->run_query(
sprintf(
'DROP TABLE IF EXISTS `%s`.`%s`',
DB_NAME,
$table
),
$assoc_args
);
}
WP_CLI::success( 'Tables dropped.' );
}
/**
* Checks the current status of the database.
*
* Runs `mysqlcheck` utility with `--check` using `DB_HOST`,
* `DB_NAME`, `DB_USER` and `DB_PASSWORD` database credentials
* specified in wp-config.php.
*
* [See docs](http://dev.mysql.com/doc/refman/5.7/en/check-table.html)
* for more details on the `CHECK TABLE` statement.
*
* ## OPTIONS
*
* [--dbuser=<value>]
* : Username to pass to mysqlcheck. Defaults to DB_USER.
*
* [--dbpass=<value>]
* : Password to pass to mysqlcheck. Defaults to DB_PASSWORD.
*
* [--<field>=<value>]
* : Extra arguments to pass to mysqlcheck. [Refer to mysqlcheck docs](https://dev.mysql.com/doc/en/mysqlcheck.html).
*
* [--defaults]
* : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
*
* ## EXAMPLES
*
* $ wp db check
* Success: Database checked.
*/
public function check( $_, $assoc_args ) {
$command = sprintf( '/usr/bin/env mysqlcheck%s %s', $this->get_defaults_flag_string( $assoc_args ), '%s' );
WP_CLI::debug( "Running shell command: {$command}", 'db' );
$assoc_args['check'] = true;
self::run(
Utils\esc_cmd( $command, DB_NAME ),
$assoc_args
);
WP_CLI::debug( 'Associative arguments: ' . json_encode( $assoc_args ), 'db' );
WP_CLI::success( 'Database checked.' );
}
/**
* Optimizes the database.
*
* Runs `mysqlcheck` utility with `--optimize=true` using `DB_HOST`,
* `DB_NAME`, `DB_USER` and `DB_PASSWORD` database credentials
* specified in wp-config.php.
*
* [See docs](http://dev.mysql.com/doc/refman/5.7/en/optimize-table.html)
* for more details on the `OPTIMIZE TABLE` statement.
*
* ## OPTIONS
*
* [--dbuser=<value>]
* : Username to pass to mysqlcheck. Defaults to DB_USER.
*
* [--dbpass=<value>]
* : Password to pass to mysqlcheck. Defaults to DB_PASSWORD.
*
* [--<field>=<value>]
* : Extra arguments to pass to mysqlcheck. [Refer to mysqlcheck docs](https://dev.mysql.com/doc/en/mysqlcheck.html).
*
* [--defaults]
* : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
*
* ## EXAMPLES
*
* $ wp db optimize
* Success: Database optimized.
*/
public function optimize( $_, $assoc_args ) {
$command = sprintf( '/usr/bin/env mysqlcheck%s %s', $this->get_defaults_flag_string( $assoc_args ), '%s' );
WP_CLI::debug( "Running shell command: {$command}", 'db' );
$assoc_args['optimize'] = true;
self::run(
Utils\esc_cmd( $command, DB_NAME ),
$assoc_args
);
WP_CLI::debug( 'Associative arguments: ' . json_encode( $assoc_args ), 'db' );
WP_CLI::success( 'Database optimized.' );
}
/**
* Repairs the database.
*
* Runs `mysqlcheck` utility with `--repair=true` using `DB_HOST`,
* `DB_NAME`, `DB_USER` and `DB_PASSWORD` database credentials
* specified in wp-config.php.
*
* [See docs](http://dev.mysql.com/doc/refman/5.7/en/repair-table.html) for
* more details on the `REPAIR TABLE` statement.
*
* ## OPTIONS
*
* [--dbuser=<value>]
* : Username to pass to mysqlcheck. Defaults to DB_USER.
*
* [--dbpass=<value>]
* : Password to pass to mysqlcheck. Defaults to DB_PASSWORD.
*
* [--<field>=<value>]
* : Extra arguments to pass to mysqlcheck. [Refer to mysqlcheck docs](https://dev.mysql.com/doc/en/mysqlcheck.html).
*
* [--defaults]
* : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
*
* ## EXAMPLES
*
* $ wp db repair
* Success: Database repaired.
*/
public function repair( $_, $assoc_args ) {
$command = sprintf( '/usr/bin/env mysqlcheck%s %s', $this->get_defaults_flag_string( $assoc_args ), '%s' );
WP_CLI::debug( "Running shell command: {$command}", 'db' );
$assoc_args['repair'] = true;
self::run(
Utils\esc_cmd( $command, DB_NAME ),
$assoc_args
);
WP_CLI::debug( 'Associative arguments: ' . json_encode( $assoc_args ), 'db' );
WP_CLI::success( 'Database repaired.' );
}
/**
* Opens a MySQL console using credentials from wp-config.php
*
* ## OPTIONS
*
* [--database=<database>]
* : Use a specific database. Defaults to DB_NAME.
*
* [--default-character-set=<character-set>]
* : Use a specific character set. Defaults to DB_CHARSET when defined.
*
* [--dbuser=<value>]
* : Username to pass to mysql. Defaults to DB_USER.
*
* [--dbpass=<value>]
* : Password to pass to mysql. Defaults to DB_PASSWORD.
*
* [--<field>=<value>]
* : Extra arguments to pass to mysql. [Refer to mysql docs](https://dev.mysql.com/doc/en/mysql-command-options.html).
*
* [--defaults]
* : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
*
* ## EXAMPLES
*
* # Open MySQL console
* $ wp db cli
* mysql>
*
* @alias connect
*/
public function cli( $_, $assoc_args ) {
$command = sprintf( '/usr/bin/env mysql%s --no-auto-rehash', $this->get_defaults_flag_string( $assoc_args ) );
WP_CLI::debug( "Running shell command: {$command}", 'db' );
if ( ! isset( $assoc_args['database'] ) ) {
$assoc_args['database'] = DB_NAME;
}
WP_CLI::debug( 'Associative arguments: ' . json_encode( $assoc_args ), 'db' );
self::run( $command, $assoc_args, null, true );
}
/**
* Executes a SQL query against the database.
*
* Executes an arbitrary SQL query using `DB_HOST`, `DB_NAME`, `DB_USER`
* and `DB_PASSWORD` database credentials specified in wp-config.php.
*
* ## OPTIONS
*
* [<sql>]
* : A SQL query. If not passed, will try to read from STDIN.
*
* [--dbuser=<value>]
* : Username to pass to mysql. Defaults to DB_USER.
*
* [--dbpass=<value>]
* : Password to pass to mysql. Defaults to DB_PASSWORD.
*
* [--<field>=<value>]
* : Extra arguments to pass to mysql. [Refer to mysql docs](https://dev.mysql.com/doc/en/mysql-command-options.html).
*
* [--defaults]
* : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
*
* ## EXAMPLES
*
* # Execute a query stored in a file
* $ wp db query < debug.sql
*
* # Check all tables in the database
* $ wp db query "CHECK TABLE $(wp db tables | paste -s -d, -);"
* +---------------------------------------+-------+----------+----------+
* | Table | Op | Msg_type | Msg_text |
* +---------------------------------------+-------+----------+----------+
* | wordpress_dbase.wp_users | check | status | OK |
* | wordpress_dbase.wp_usermeta | check | status | OK |
* | wordpress_dbase.wp_posts | check | status | OK |
* | wordpress_dbase.wp_comments | check | status | OK |
* | wordpress_dbase.wp_links | check | status | OK |
* | wordpress_dbase.wp_options | check | status | OK |
* | wordpress_dbase.wp_postmeta | check | status | OK |
* | wordpress_dbase.wp_terms | check | status | OK |
* | wordpress_dbase.wp_term_taxonomy | check | status | OK |
* | wordpress_dbase.wp_term_relationships | check | status | OK |
* | wordpress_dbase.wp_termmeta | check | status | OK |
* | wordpress_dbase.wp_commentmeta | check | status | OK |
* +---------------------------------------+-------+----------+----------+
*
* # Pass extra arguments through to MySQL
* $ wp db query 'SELECT * FROM wp_options WHERE option_name="home"' --skip-column-names
* +---+------+------------------------------+-----+
* | 2 | home | http://wordpress-develop.dev | yes |
* +---+------+------------------------------+-----+
*/
public function query( $args, $assoc_args ) {
$command = sprintf( '/usr/bin/env mysql%s --no-auto-rehash', $this->get_defaults_flag_string( $assoc_args ) );
WP_CLI::debug( "Running shell command: {$command}", 'db' );
$assoc_args['database'] = DB_NAME;
// The query might come from STDIN.
if ( ! empty( $args ) ) {
$assoc_args['execute'] = $args[0];
}
if ( isset( $assoc_args['execute'] ) ) {
// Ensure that the SQL mode is compatible with WPDB.
$assoc_args['execute'] = $this->get_sql_mode_query( $assoc_args ) . $assoc_args['execute'];
}
WP_CLI::debug( 'Associative arguments: ' . json_encode( $assoc_args ), 'db' );
self::run( $command, $assoc_args );
}
/**
* Exports the database to a file or to STDOUT.
*
* Runs `mysqldump` utility using `DB_HOST`, `DB_NAME`, `DB_USER` and
* `DB_PASSWORD` database credentials specified in wp-config.php. Accepts any valid `mysqldump` flags.
*
* ## OPTIONS
*
* [<file>]
* : The name of the SQL file to export. If '-', then outputs to STDOUT. If
* omitted, it will be '{dbname}-{Y-m-d}-{random-hash}.sql'.
*
* [--dbuser=<value>]
* : Username to pass to mysqldump. Defaults to DB_USER.
*
* [--dbpass=<value>]
* : Password to pass to mysqldump. Defaults to DB_PASSWORD.
*
* [--<field>=<value>]
* : Extra arguments to pass to mysqldump. [Refer to mysqldump docs](https://dev.mysql.com/doc/en/mysqldump.html#mysqldump-option-summary).
*
* [--tables=<tables>]
* : The comma separated list of specific tables to export. Excluding this parameter will export all tables in the database.
*
* [--exclude_tables=<tables>]
* : The comma separated list of specific tables that should be skipped from exporting. Excluding this parameter will export all tables in the database.
*
* [--include-tablespaces]
* : Skips adding the default --no-tablespaces option to mysqldump.
*
* [--porcelain]
* : Output filename for the exported database.
*
* [--defaults]
* : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
*
* ## EXAMPLES
*
* # Export database with drop query included
* $ wp db export --add-drop-table
* Success: Exported to 'wordpress_dbase-db72bb5.sql'.
*
* # Export certain tables
* $ wp db export --tables=wp_options,wp_users
* Success: Exported to 'wordpress_dbase-db72bb5.sql'.
*
* # Export all tables matching a wildcard
* $ wp db export --tables=$(wp db tables 'wp_user*' --format=csv)
* Success: Exported to 'wordpress_dbase-db72bb5.sql'.
*
* # Export all tables matching prefix
* $ wp db export --tables=$(wp db tables --all-tables-with-prefix --format=csv)
* Success: Exported to 'wordpress_dbase-db72bb5.sql'.
*
* # Export certain posts without create table statements
* $ wp db export --no-create-info=true --tables=wp_posts --where="ID in (100,101,102)"
* Success: Exported to 'wordpress_dbase-db72bb5.sql'.
*
* # Export relating meta for certain posts without create table statements
* $ wp db export --no-create-info=true --tables=wp_postmeta --where="post_id in (100,101,102)"
* Success: Exported to 'wordpress_dbase-db72bb5.sql'.
*
* # Skip certain tables from the exported database
* $ wp db export --exclude_tables=wp_options,wp_users
* Success: Exported to 'wordpress_dbase-db72bb5.sql'.
*
* # Skip all tables matching a wildcard from the exported database
* $ wp db export --exclude_tables=$(wp db tables 'wp_user*' --format=csv)
* Success: Exported to 'wordpress_dbase-db72bb5.sql'.
*
* # Skip all tables matching prefix from the exported database
* $ wp db export --exclude_tables=$(wp db tables --all-tables-with-prefix --format=csv)
* Success: Exported to 'wordpress_dbase-db72bb5.sql'.
*
* # Export database to STDOUT.
* $ wp db export -
* -- MySQL dump 10.13 Distrib 5.7.19, for osx10.12 (x86_64)
* --
* -- Host: localhost Database: wpdev
* -- ------------------------------------------------------
* -- Server version 5.7.19
* ...
*
* @alias dump
*/
public function export( $args, $assoc_args ) {
if ( ! empty( $args[0] ) ) {
$result_file = $args[0];
} else {
// phpcs:ignore WordPress.WP.AlternativeFunctions.rand_mt_rand -- WordPress is not loaded.
$hash = substr( md5( mt_rand() ), 0, 7 );
$result_file = sprintf( '%s-%s-%s.sql', DB_NAME, date( 'Y-m-d' ), $hash ); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
}
$stdout = ( '-' === $result_file );
$porcelain = Utils\get_flag_value( $assoc_args, 'porcelain' );
// Bail if both porcelain and STDOUT are set.
if ( $stdout && $porcelain ) {
WP_CLI::error( 'Porcelain is not allowed when output mode is STDOUT.' );
}
if ( ! $stdout ) {
$assoc_args['result-file'] = $result_file;
}
$mysqldump_binary = Utils\force_env_on_nix_systems( 'mysqldump' );
$support_column_statistics = exec( $mysqldump_binary . ' --help | grep "column-statistics"' );
/*
* In case that `--default-character-set` is not given and `DB_CHARSET` is `utf8`,
* we try to deduce what the actual character set for the posts table of the
* current database is and use `utf8mb4` as a `default-character-set` if that
* seems like the safer default, to ensure emojis are encoded correctly.
*/
if (
! isset( $assoc_args['default-character-set'] )
&&
( defined( 'DB_CHARSET' ) && self::ENCODING_UTF8 === constant( 'DB_CHARSET' ) )
&&
self::ENCODING_UTF8MB4 === $this->get_posts_table_charset( $assoc_args )
) {
WP_CLI::debug( 'Setting missing default character set to ' . self::ENCODING_UTF8MB4, 'db' );
$assoc_args['default-character-set'] = self::ENCODING_UTF8MB4;
}
$initial_command = sprintf( "{$mysqldump_binary}%s ", $this->get_defaults_flag_string( $assoc_args ) );
WP_CLI::debug( "Running initial shell command: {$initial_command}", 'db' );
$default_arguments = [ '%s' ];
if ( $support_column_statistics ) {
$default_arguments[] = '--skip-column-statistics';
}
if ( ! Utils\get_flag_value( $assoc_args, 'include-tablespaces', false ) ) {
$default_arguments[] = '--no-tablespaces';
}
$command = $initial_command . implode( ' ', $default_arguments );
$command_esc_args = [ DB_NAME ];
if ( isset( $assoc_args['tables'] ) ) {
$tables = explode( ',', trim( $assoc_args['tables'], ',' ) );
unset( $assoc_args['tables'] );
$command .= ' --tables';
foreach ( $tables as $table ) {
$command .= ' %s';
$command_esc_args[] = trim( $table );
}
}
$exclude_tables = Utils\get_flag_value( $assoc_args, 'exclude_tables' );
if ( isset( $exclude_tables ) ) {
$tables = explode( ',', trim( $assoc_args['exclude_tables'], ',' ) );
unset( $assoc_args['exclude_tables'] );
foreach ( $tables as $table ) {
$command .= ' --ignore-table';
$command .= ' %s';
$command_esc_args[] = trim( DB_NAME . '.' . $table );
}
}
$escaped_command = call_user_func_array( '\WP_CLI\Utils\esc_cmd', array_merge( [ $command ], $command_esc_args ) );
// Remove parameters not needed for SQL run.
unset( $assoc_args['porcelain'] );
WP_CLI::debug( 'Associative arguments: ' . json_encode( $assoc_args ), 'db' );
self::run( $escaped_command, $assoc_args );
if ( $porcelain ) {
WP_CLI::line( $result_file );
} elseif ( ! $stdout ) {
WP_CLI::success( sprintf( "Exported to '%s'.", $result_file ) );
}
}
/**
* Get the current character set of the posts table.
*
* @param array Associative array of associative arguments.
* @return string Posts table character set.
*/
private function get_posts_table_charset( $assoc_args ) {
$query = 'SELECT CCSA.character_set_name '
. 'FROM information_schema.`TABLES` T, '
. 'information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA '
. 'WHERE CCSA.collation_name = T.table_collation '
. "AND T.table_schema = '" . DB_NAME . "' "
. "AND T.table_name LIKE '%\_posts';";
list( $stdout, $stderr, $exit_code ) = self::run(
sprintf(
'/usr/bin/env mysql%s --no-auto-rehash --batch --skip-column-names',
$this->get_defaults_flag_string( $assoc_args )
),
[ 'execute' => $query ],
false
);
if ( $exit_code ) {
WP_CLI::warning(
'Failed to get current character set of the posts table.'
. ( ! empty( $stderr ) ? " Reason: {$stderr}" : '' )
);
return self::ENCODING_UTF8MB4;
}
$stdout = trim( $stdout );
WP_CLI::debug( "Detected character set of the posts table: {$stdout}.", 'db' );
return $stdout;
}
/**
* Imports a database from a file or from STDIN.
*
* Runs SQL queries using `DB_HOST`, `DB_NAME`, `DB_USER` and
* `DB_PASSWORD` database credentials specified in wp-config.php. This
* does not create database by itself and only performs whatever tasks are
* defined in the SQL.
*
* ## OPTIONS
*
* [<file>]
* : The name of the SQL file to import. If '-', then reads from STDIN. If omitted, it will look for '{dbname}.sql'.
*
* [--dbuser=<value>]
* : Username to pass to mysql. Defaults to DB_USER.
*
* [--dbpass=<value>]
* : Password to pass to mysql. Defaults to DB_PASSWORD.
*
* [--<field>=<value>]
* : Extra arguments to pass to mysql. [Refer to mysql binary docs](https://dev.mysql.com/doc/refman/8.0/en/mysql-command-options.html).
*
* [--skip-optimization]
* : When using an SQL file, do not include speed optimization such as disabling auto-commit and key checks.
*
* [--defaults]
* : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
*
* ## EXAMPLES
*
* # Import MySQL from a file.
* $ wp db import wordpress_dbase.sql
* Success: Imported from 'wordpress_dbase.sql'.
*/
public function import( $args, $assoc_args ) {
if ( ! empty( $args[0] ) ) {
$result_file = $args[0];
} else {
$result_file = sprintf( '%s.sql', DB_NAME );
}
// Process options to MySQL.
$mysql_args = array_merge(
[ 'database' => DB_NAME ],
self::get_dbuser_dbpass_args( $assoc_args ),
self::get_mysql_args( $assoc_args )
);
if ( '-' !== $result_file ) {
if ( ! is_readable( $result_file ) ) {
WP_CLI::error( sprintf( 'Import file missing or not readable: %s', $result_file ) );
}
$query = Utils\get_flag_value( $assoc_args, 'skip-optimization' )
? 'SOURCE %s;'
: 'SET autocommit = 0; SET unique_checks = 0; SET foreign_key_checks = 0; SOURCE %s; COMMIT;';
$query = $this->get_sql_mode_query( $assoc_args ) . $query;
$mysql_args['execute'] = sprintf( $query, $result_file );
} else {
$result_file = 'STDIN';
}
$command = sprintf( '/usr/bin/env mysql%s --no-auto-rehash', $this->get_defaults_flag_string( $assoc_args ) );
WP_CLI::debug( "Running shell command: {$command}", 'db' );
WP_CLI::debug( 'Associative arguments: ' . json_encode( $assoc_args ), 'db' );
self::run( $command, $mysql_args );
WP_CLI::success( sprintf( "Imported from '%s'.", $result_file ) );
}
/**
* Lists the database tables.
*
* Defaults to all tables registered to the $wpdb database handler.
*
* ## OPTIONS
*
* [<table>...]
* : List tables based on wildcard search, e.g. 'wp_*_options' or 'wp_post?'.
*
* [--scope=<scope>]
* : Can be all, global, ms_global, blog, or old tables. Defaults to all.
*
* [--network]
* : List all the tables in a multisite install.
*
* [--all-tables-with-prefix]
* : List all tables that match the table prefix even if not registered on $wpdb. Overrides --network.
*
* [--all-tables]
* : List all tables in the database, regardless of the prefix, and even if not registered on $wpdb. Overrides --all-tables-with-prefix.
*
* [--format=<format>]
* : Render output in a particular format.
* ---
* default: list
* options:
* - list
* - csv
* ---
*
* ## EXAMPLES
*
* # List tables for a single site, without shared tables like 'wp_users'
* $ wp db tables --scope=blog --url=sub.example.com
* wp_3_posts
* wp_3_comments
* wp_3_options
* wp_3_postmeta
* wp_3_terms
* wp_3_term_taxonomy
* wp_3_term_relationships
* wp_3_termmeta
* wp_3_commentmeta
*
* # Export only tables for a single site
* $ wp db export --tables=$(wp db tables --url=sub.example.com --format=csv)
* Success: Exported to wordpress_dbase.sql
*
* @when after_wp_load
*/
public function tables( $args, $assoc_args ) {
$format = Utils\get_flag_value( $assoc_args, 'format' );
unset( $assoc_args['format'] );
if ( empty( $args ) && empty( $assoc_args ) ) {
$assoc_args['scope'] = 'all';
}
$tables = Utils\wp_get_table_names( $args, $assoc_args );
if ( 'csv' === $format ) {
WP_CLI::line( implode( ',', $tables ) );
} else {
foreach ( $tables as $table ) {
WP_CLI::line( $table );
}
}
}
/**
* Displays the database name and size.
*
* Display the database name and size for `DB_NAME` specified in wp-config.php.
* The size defaults to a human-readable number.
*
* Available size formats include:
* * b (bytes)
* * kb (kilobytes)
* * mb (megabytes)
* * gb (gigabytes)
* * tb (terabytes)
* * B (ISO Byte setting, with no conversion)
* * KB (ISO Kilobyte setting, with 1 KB = 1,000 B)
* * KiB (ISO Kibibyte setting, with 1 KiB = 1,024 B)
* * MB (ISO Megabyte setting, with 1 MB = 1,000 KB)
* * MiB (ISO Mebibyte setting, with 1 MiB = 1,024 KiB)
* * GB (ISO Gigabyte setting, with 1 GB = 1,000 MB)
* * GiB (ISO Gibibyte setting, with 1 GiB = 1,024 MiB)
* * TB (ISO Terabyte setting, with 1 TB = 1,000 GB)
* * TiB (ISO Tebibyte setting, with 1 TiB = 1,024 GiB)
*
* ## OPTIONS
*
* [--size_format=<format>]
* : Display the database size only, as a bare number.
* ---
* options:
* - b
* - kb
* - mb
* - gb
* - tb
* - B
* - KB
* - KiB
* - MB
* - MiB
* - GB
* - GiB
* - TB
* - TiB
* ---
*
* [--tables]
* : Display each table name and size instead of the database size.
*
* [--human-readable]
* : Display database sizes in human readable formats.
*
* [--format=<format>]
* : Render output in a particular format.
* ---
* options:
* - table
* - csv
* - json
* - yaml
* ---
*
* [--scope=<scope>]
* : Can be all, global, ms_global, blog, or old tables. Defaults to all.
*
* [--network]
* : List all the tables in a multisite install.
*
* [--decimals=<decimals>]
* : Number of digits after decimal point. Defaults to 0.
*
* [--all-tables-with-prefix]
* : List all tables that match the table prefix even if not registered on $wpdb. Overrides --network.
*
* [--all-tables]
* : List all tables in the database, regardless of the prefix, and even if not registered on $wpdb. Overrides --all-tables-with-prefix.
*
* [--order=<order>]
* : Ascending or Descending order.
* ---
* default: asc
* options:
* - asc
* - desc
* ---
*
* [--orderby=<orderby>]
* : Order by fields.
* ---
* default: name
* options:
* - name
* - size
* ---
*
* ## EXAMPLES
*
* $ wp db size
* +-------------------+------+
* | Name | Size |
* +-------------------+------+
* | wordpress_default | 6 MB |
* +-------------------+------+
*
* $ wp db size --tables
* +-----------------------+-------+
* | Name | Size |
* +-----------------------+-------+
* | wp_users | 64 KB |
* | wp_usermeta | 48 KB |
* | wp_posts | 80 KB |
* | wp_comments | 96 KB |
* | wp_links | 32 KB |
* | wp_options | 32 KB |
* | wp_postmeta | 48 KB |
* | wp_terms | 48 KB |
* | wp_term_taxonomy | 48 KB |
* | wp_term_relationships | 32 KB |
* | wp_termmeta | 48 KB |
* | wp_commentmeta | 48 KB |
* +-----------------------+-------+
*
* $ wp db size --size_format=b
* 5865472
*
* $ wp db size --size_format=kb
* 5728
*
* $ wp db size --size_format=mb
* 6
*
* @when after_wp_load
*/
public function size( $args, $assoc_args ) {
global $wpdb;
$format = Utils\get_flag_value( $assoc_args, 'format' );
$size_format = Utils\get_flag_value( $assoc_args, 'size_format' );
$human_readable = Utils\get_flag_value( $assoc_args, 'human-readable', false );
$tables = Utils\get_flag_value( $assoc_args, 'tables' );
$tables = ! empty( $tables );
$all_tables = Utils\get_flag_value( $assoc_args, 'all-tables' );
$all_tables_with_prefix = Utils\get_flag_value( $assoc_args, 'all-tables-with-prefix' );
$order = Utils\get_flag_value( $assoc_args, 'order', 'asc' );
$orderby = Utils\get_flag_value( $assoc_args, 'orderby', null );
if ( ! is_null( $size_format ) && $human_readable ) {
WP_CLI::error( 'Cannot use --size_format and --human-readable arguments at the same time.' );
}
unset( $assoc_args['format'] );
unset( $assoc_args['size_format'] );
unset( $assoc_args['human-readable'] );
unset( $assoc_args['tables'] );
if ( empty( $args ) && empty( $assoc_args ) ) {
$assoc_args['scope'] = 'all';
}
// Build rows for the formatter.
$rows = [];
$fields = [ 'Name', 'Size' ];
$default_unit = ( empty( $size_format ) && ! $human_readable ) ? ' B' : '';
if ( $tables || $all_tables || $all_tables_with_prefix ) {
// Add all of the table sizes.
foreach ( Utils\wp_get_table_names( $args, $assoc_args ) as $table_name ) {
// Get the table size.