Skip to content

Commit

Permalink
Database optimizations (#84)
Browse files Browse the repository at this point in the history
* Add Database class and CLI option to run optimizations

* Add multi-site support
  • Loading branch information
akshitsethi authored Apr 21, 2021
1 parent 3f69c9c commit 6bf85fc
Show file tree
Hide file tree
Showing 5 changed files with 818 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
VERSION := 3.29.4
VERSION := 3.30.0
PLUGINSLUG := woocart-defaults
SRCPATH := $(shell pwd)/src

Expand Down
81 changes: 81 additions & 0 deletions src/classes/CLICommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

namespace Niteo\WooCart\Defaults {

use Niteo\WooCart\Defaults\Database;
use Niteo\WooCart\Defaults\Generators\Product;
use Niteo\WooCart\Defaults\Importers\SellingLimit;
use Niteo\WooCart\Defaults\Importers\WooPage;
Expand Down Expand Up @@ -444,5 +445,85 @@ public function filesystem_lock( $args, $assoc_args ) {
WP_CLI::error( $e );
}
}

/**
* Checks and applies the optimizations for the database.
*
* ## OPTIONS
*
* <action>
* : Action to be performed.
*
* [--network]
* : Multi-site support.
*
* ---
* options:
* - optimize
*
* ## EXAMPLES
*
* wp wcd db optimize
*
* @codeCoverageIgnore
* @param $args array list of command line arguments.
* @param $assoc_args array of named command line keys.
* @throws WP_CLI\ExitException on wrong command.
*/
public function db( $args, $assoc_args ) {
try {
list($action) = $args;

if ( 'optimize' === $action ) {
$db = new Database();

/**
* Optimizations.
*
* 1. Run analyze query on 3 tables (posts, postmeta, and options)
* 2. Switch table engine to InnoDB
* 3. Add index on columns
*/
if ( isset( $assoc_args['network'] ) ) {
if ( is_multisite() ) {
$sites = get_sites(
array(
'fields' => 'ids',
)
);

foreach ( $sites as $site ) {
switch_to_blog( $site );

// Fetch details for the current site.
$site_info = get_blog_details( $site );

WP_CLI::log( '' );
WP_CLI::log( '--> Running optimisations for ' . $site_info->blogname . ' (ID: ' . $site . ')' );
WP_CLI::log( '' );

$db->analyze_tables(); // 1
$db->switch_to_innodb(); // 2
$db->add_indexes(); // 3

restore_current_blog();
}

return;
} else {
WP_CLI::error( 'Multi-site is not enabled. Please try again without the --network option.' );
return;
}
}

$db->analyze_tables(); // 1
$db->switch_to_innodb(); // 2
$db->add_indexes(); // 3
}
} catch ( \Exception $e ) {
WP_CLI::line( 'There was an error processing your request.' );
WP_CLI::error( $e->getMessage() );
}
}
}
}
Loading

0 comments on commit 6bf85fc

Please sign in to comment.