Fixing WordPress Errors

Let’s face it. At some point, while running your WordPress site, you will run into issues and errors and may ultimately have to ask yourself…

A backup & restore may not resolve your issue, and a plugin may not display itself as the source of your problem, at least, not immediately. It’s hard to tell exactly what is causing your site issues just by looking at it. This can get pretty serious in some cases and can range from a large variety of issues. In this tutorial we will cover the basics on troubleshooting problems with your WordPress installation to try and correct common issues seen with WordPress. The first place you need to look for the source of your problem is within the error log.

 

The most common or likely seen error log used within WordPress investigations does not actually stem from WordPress but rather from your PHP installation on the server. The php.ini file used to control PHP settings for your site will determine if and where the error log is reporting. If this is enabled you can usually find the error log in the directory (or folder) of your WordPress installation. In most cases, this file is titled error_log but is dependent on the setting in the php.ini file. You can also find the WordPress PHP error log (if enabled) within the wp-content folder in a file called php.error_log. If you see neither of these and your site is not loading properly, you need to enable debugging mode or enable PHP logging in your php.ini.

 

You can enable debugging for WordPress within the wp-config.php file. This is essential when trying to determine why a site is no longer loading or is erroring. You may never understand why a site does not load without seeing the errors generated. To better see what is occurring simply edit the following line within your wp-config.php file:

define('WP_DEBUG', false);

And change the false to true:

define('WP_DEBUG', true);

Changing the value to true enables debug mode and will display any errors site code directly on the page. This can be useful when trying to track down site issues or to see if upgrades have created any new issues. If you change PHP versions and the site no longer loads this method  will tell you why. Wp-config.php is also the location where you can enable the WordPress PHP error log and log directly to a file rather than printing to the screen. You can do this by adding the following code to the wp-config file:

define('WP_DEBUG_LOG', true);This code creates the WordPress PHP error log (php.error_log) if errors are present and are being generated. You can find this file within the wp-content folder of your WordPress installation. You may not see this error file if errors are not being generated so the lack of presence, after enabling this setting, may mean no errors are being reported. For instance, if your .htaccess file has a syntax error the php.error_log will not show the error because it is not a PHP related error.

If you would rather enable PHP error logging you can add values to the php.ini for the domain or via .htaccess if your configuration supports them:

Open your site’s php.ini file. If you are unsure where this is located, you can use a phpinfo page to show the location or you can also run the following in command line:

cpUser=`pwd | cut -d/ -f3`; for i in `pwd`; do touch $i/phpinfo.php; chown $cpUser. $i/phpinfo.php ; echo "<?php phpinfo(); ?>" > $i/phpinfo.php; done

Manually create a phpinfo.php file within your sites public_html folder with the following code.

<?php
// Show all information
phpinfo();
?>
Afterwards, access this file via a browser at the location you created it. You will find the php.ini path under Loaded Configuration File:

With a PHP info file, you will find the php.ini path under Loaded Configuration File

Once you find this location, edit the file and add the following code if it does not exist:

;;; log php errors
display_startup_errors = false
display_errors = false
html_errors = false
log_errors = true
track_errors = true
error_log = /home/USER/logs/error_log
error_reporting = E_ALL | E_STRICT

You can change the path for error_log to wherever you want this to be stored within your users home directory. The WordPress install is bound to the same access rights as the user installing it so it will not have the permissions to write outside their home directory.

On older setups you can change the logging information via .htaccess if your configuration supports php_flags (using DSO aka as Data Source Object)

# log php errors
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_flag  log_errors on
php_value error_log /home/path/logs/error_log
Most likely newer and up-to-date configurations are not using DSO and you will need to modify this via the php.ini file.

 

To understand how to read the output of these logs look at the following entry:

[09-Sep-2018 22:57:20 UTC] PHP Fatal error:  Allowed memory size of 41943040 bytes exhausted (tried to allocate 32768 bytes) in home/USERNAME/public_html/wp-content/plugins/wordpress-seo/inc/class-wpseo-meta.php on line 477

You can see the date and timestamp followed by the general message and path this stems from. This tells you most of the details you will need to determine where the problem lies. You can see from the timestamp of this error when the error is occurring and if that relates to the current issue or if it was a different error. The path will usually show if this stems from a plugin or theme and the location of the software generating the error. This will even display the line in the document or file that triggered the error which can be further reviewed by your sites developer.

 

The “fatal error” is the most common type of error seen and the cause can vary from coding, like “undefined function”, indicate the function and problematic line of code to memory errors (like the one used in the above example). This usually occurs when the server has run out of memory or the PHP memory limit is not set high enough to run the code’s requirements. To fix these errors you may need to update software (themes and plugins usually) as it may be using deprecated code and or functions. You may also need to increase the PHP memory limit or locate any heavy resource usage on the server that may be consuming memory.

This generally means there is an issue with the database in use or the configuration of your WordPress setup. This could mean your database is corrupt or the configuration settings used in your wp-config are not correct or have been modified. Check your wp-config file has the correct credentials and syntax to ensure your database can communicate with your WordPress files. You may also see this error when the server has heavy load or the MySQL service is down. You’ll need to investigate resource usage on the server to determine why.

A standard 404 error means your server could not locate the file being called by the software in use on the domain. This usually occurs when ownership or permissions are incorrect, the file path is called incorrectly or the file is completely missing.

 

WordPress can sometimes run for a while without issue but some common errors can be solved with a little bit of background. As always our helpful support experts are here to assist with any WordPress related errors. Should you need assistance with troubleshooting your WordPress installation and we even offer a Managed WordPress hosting platform with WordPress error experts to investigate many issues.

 

Change Primary Domain in WHM

If you use multiple aliases ( previously called parked domains) within a cPanel account, you may find yourself wanting to change the main domain used for the cPanel account containing these domains. Changing the primary domain is desirable for multiple reasons and many times occurs when the site in use switches from one TLD to another (i.e., .net to .com). You may desire to change this if the name of your company or site changes. It can also occur when a domain is no longer used, or when the domain is removed from an account. Sometimes the wrong site name was set to be the primary domain, to begin with (we all make mistakes, right?). Whatever the reason for changing the primary domain, the change is relatively simple to make. However, it does make some potentially significant changes on the account that could create the need for additional changes for site functionality, so it is best to understand what these changes are before making this decision wholeheartedly.

Email & DNS

This change will modify multiple factors of the domain including (if you so choose) the cPanel username (which is usually not advised), the FTP username and MySQL users. Making this change will delete any custom DNS records if you are using custom nameservers setup within WHM and hosting your DNS. If using custom nameservers be sure to go into the DNS editor and take a screenshot of your DNS for the domain or copy the records to a text document before making this change. An additional effect is that all e-mail accounts change to reflect the new domain, for example changing the primary domain from yourdomain.com to newdomain.com will change admin@yourdomain.com to admin@newdomain.com. You may then need to update the e-mail address and username (for both incoming and outgoing servers within your e-mail client) on any devices that e-mail account is set up on.

Aliases

If you already added an alias ( a parked domain which shares content) or addon domain (which has its content apart from the main domain), you need to remove it first. Meaning you may need to save the content and site data for addon domains elsewhere on the server until after this change. You will also want to remove any subdomains of your primary domain name before you can change it as well. The following can be used as a basic guide to remove these as the process for each is the same:

Log into cPanel: yourdomain.com/cpanel
Navigate to and click on ‘Aliases’ (this may be listed as parked domains on older versions of WHM) (or you could locate subdomains or addon domains)
Locate the alias you want to be removed and click remove.

SSL Certificates

If you have an SSL certificate applied to this account, you will end up revoking the SSL installed for the current primary domain by removing it. In these cases a new SSL is necessary. If you are using AutoSSL, you may need to re-run to ensure all sites have an SSL installed appropriately. If you have purchased an SSL, you will need to order a new SSL for the new domain name.

Changing the primary domain may require modifying the siteurl if you are using WordPress and this could break the installation until you change the URL.

Hostname

Often changing the primary domain is confused with the hostname of the server, these are separate changes. However, for clarity, this does not change the hostname of the server (your server name) and does not change the name of the server within your manage.liquidweb.com account either. Changing the primary domain will only change data related to the cPanel account and its associated user. While most changes are made within the cPanel account for the user, this change can not be made within the cPanel account for the domain. Changing the primary domain is done via WHM which requires root level access.

Backups

Before making any significant changes on your server, its advised to have the ability to revert in case of mistakes. Create a full website backup via cPanel for the account you want to modify. You can find instructions on how to do this here.

Ensure that you have available backups for the domain within the backup restoration area in WHM. These will be available if you already have backups configured within WHM. If you use alternate means to back up your accounts, ensure you have available backups before making this change.

To change the primary domain, you will need to do this within WHM.

  1. You can access WHM by using the servers IP followed by the port 2087, or if DNS is set up for the hostname, you can access WHM by using the hostname/whm. Another method is to use a domain name on the server followed by /whm:Examples:
    • 192.168.1.1:2087 (replace the IP with your servers IP)
    • https://hostname.com/whm
    • https://domainname.com/whm
  2. To change the primary domain login to WHM using the root user and root password:To change the primary domain log in to WHM using root.
  3. After logging the top right of your window is a search bar (you may need to expand this menu). Access List Accounts via the search bar and click on the link it displays.Find the primary domain in WHM by searching for "List Accounts".
  4. Find the user you want to modify by typing in the name of the account in the new search bar that opens. Then click the + symbol next to the user:In the WHM account click the "modify account" button to change the primary domain.
  5. Finally, click the Modify Account button:The 'modify account' button changes the primary domain in WHM.
  6. Change the Primary Domain to the domain you want in its place:WHM screen indicates where to change the primary domain.
  7. Decide if you’re going to adjust options. You could decide to modify the databases associated with the domain to include new prefixes, for example, changing the Username.
Note:
If you are not familiar with what these changes mean. It’s highly recommended NOT to change the cPanel username. Since the username is tied to the database name, you may get database errors when altering. Changing the username requires further site coding and configuration by your developer. Your WordPress or CMS configuration file will need to be updated if the username is changed creating new database names.

After making this change, you may find that you want to keep the old e-mail addresses used by the old primary domain. If this is the case, the fix is simple. Park the old domain on the new one via an alias and create new e-mail accounts under the old domain name within CPanel’s e-mail accounts section. This way you can still use your existing e-mail accounts and also change the primary domain.

You have successfully changed the primary domain for this account! Our Support Teams are filled with talented admins with an intimate knowledge of multiple web hosting technologies, especially those discussed in this article. If you are Fully Managed VPS customer and you are uncomfortable with performing the outlined steps, we are a phone call, chat or ticket away from assisting you with this process

MySQL Performance: Converting MySQL to MariaDB

As we explored in our previous article of our MySQL Perfomance Series: MySQL vs. MariaDB there are very few downsides to using MariaDB over standard MySQL. Our high-availbility MariaDBs have proven itself to be a worthy successor with easily migitated drawbacks.  As the last article in our series we will focus on upgrading to various MySQL and MariaDB version on the following servers:

CentOS 6/7

Ubuntu 14.04/16.04

Choosing a MariaDB Upgrade Plan

Selecting the right upgrade plan requires determining which version of MySQL is running on the intended system. A universal method of determining what version of MySQL the server is currently running is to query the server itself to report the version. This works the same despite the Linux distribution running on the server:

mysql -h localhost -e 'SHOW VARIABLES LIKE "version"\G'

Example Output:

~ $ mysql -h localhost -p -e 'SHOW VARIABLES LIKE "version"\G'
*************************** 1. row ***************************
Variable_name: version
Value: 5.5.61-MariaDB
 Be sure not you are connecting to a local server when performing this check.

Once you’ve identified your MySQL version, use the key below to locate the correct upgrade procedure for your particular server. Some versions of MySQL require upgrading to MariaDB 5.5 before upgrading to MariaDB 10.x versions.

Upgrading from MySQL  to MariaDB

The upgrade process is similar between most server types. There are differences with the specific commands that are executed, but the overall procedure follows this General Upgrade Procedure:

  1. Schedule accurate downtime.
  2. Ensure adequate backups.
  3. Remove the existing MySQL binaries/packages.
  4. Install the correct MariaDB repository.
  5. Clear repository caches to expunge old package data.
  6. Install MariaDB packages via the system’s package manager.
  7. Start MariaDB by starting the MySQL service.
  8. Run MySQL upgrade script.
  9. Confirm MySQL databases are accessible and data is correct

We’ve included specific procedures below for various Liquid Web systems. Before choosing your applicable upgrade procedure, let us review the first two steps in the above General Upgrade Procedure. These steps are generally universal and are critical to the success of any maintenance plan.

Schedule Accurate Downtime

Scheduling proper maintenance windows to perform changes affecting production environments can be tricky. The maintenance event window must include enough time to perform all necessary tasks in the maintenance plan, plus any troubleshooting and extra time to complete the Reversion Plan if needed.

When calculating MySQL maintenance windows, double your estimated calculation plus 20 mins.

Ensure Adequate Backups

There is more to a maintenance backup plan than just backing up files and databases. It’s also necessary to form a Reversion Plan, which outlines the process to restore the environment to its original state before the start of the maintenance.
Maintenance events can sometimes lead to unforeseen issues with the alternative of reverting to backups. Having both a valid backup plan and a valid reversion plan to restore services is a critical component of successful maintenance. Below are outlines of both a Sample Backup Plan and a Sample Reversion Plan which can be used in conjunction with this article’s upgrade procedure outlines.

Sample Backup Plan

Create a backup of all databases.

mysqldump --all-databases –add-drop-database > all-databases-backup.sqlThis command has no visible output unless errors occur. The above command creates a single file backup of all databases used for easy restoration when using the –add-drop-database flag. This .sql file can re-imported into MySQL for deletion and re-creations of all databases. The file created is named all-databases-backup.sql and will be needed later in the Sample Reversion Plan. Be sure you have enough space when making a MySQL backup of all your databases. Table locking occurs when performing a MySQL backup.

Create a backup of MySQL’s configuration file.

cp -p /etc/my.cnf{,.bak}This command has no visible output unless errors occur. The above command will create an exact copy of /etc/my.cnf named /etc/my.cnf.bak which can be used to restore the configuration if needed.

Sample Reversion Plan
Step 1: Restore all databases into MySQL mysql < all-databases-backup.sqlThis command has no visible output unless errors occur.   Step 2:Preserve existing config by renaming /etc/my.cnf to /etc/my.cnf.bak mv -p /etc/my.cnf{,.bad}This command has no visible output unless errors occur.   Step 3: Copy the /etc/my.cnf.bak file to /etc/my.cnf cp -p /etc/my.cnf{.bak,}This command has no visible output unless errors occur.   Step 4: Restart MySQL Service service mysqld restart Example Output:~ $ service mysqld restart
Stopping mysqld: [ OK ] Starting mysqld: [ OK ]
Mysqld has switched to mysql.

MySQL to MariaDB on CentOS 6/7 with cPanel

All Liquid Web cPanel server images include MariaDB 5.5 already installed. This includes both CentOS 6 and CentOS 7 server images. There is no need to upgrade unless the MariaDB 10.x series is required. For a manual upgrade, procedures as provided by MariaDB here: Upgrading from MariaDB 5.5 to MariaDB 10.0, otherwise, cPanel provides an easy point-&-click interface which does all the heavy lifting for you. Follow one of the procedures below in either TexT Only form or Graphical form.

With upgrades it best to schedule off of peak functioning hours.

cPanel MariaDB Upgrade Instructions:

Step A) Confirm backups are present before proceeding at the scheduled time.

Step B) Login to WHM and load the MySQL/MariaDB Upgrades page:

WHM allows you to upgrade your MySQL versions with just a few clicks.

 Use the quick search box on the left and type in: mysql upgrade

 Locate and Click the MySQL/MariaDB Upgrades link.

 Selected your desired version of MariaDB.        

 Click the Next button.

Step C) Wait for the Upgrade Warnings” page to finish loading.

WHM will warn you of any potential consequences before upgrading MySQL.

① Read & acknowledge each warning message by enabling each checkbox.

② Click the Continue button.

Step D) Wait for the Upgrade Type” page to finish loading.

WHM prompts for the upgrade type for MySQL.

① Select Unattended Upgrade for a seamless upgrade experience.

② Click the Continue button.

Step E) Wait for the Upgrade Process to complete.

WHM browser can be closed without interrupting MySQL update.MySQL to MariaDB on CentOS 7 with Plesk Onyx 17

All Liquid Web CentOS 7 server images include MariaDB 5.5 already installed, including our CentOS 7 Plesk Onyx 17 servers. There is no need to upgrade unless the MariaDB 10.x series is required. In these cases, follow the standard MariaDB Plesk Upgrade Procedures here: How to upgrade MySQL 5.5 to 5.6/5.7 or MariaDB 5.5 to 10.0/10.1/10.2 on Linux

 

MySQL 5.1-5.5 to MariaDB 5.5 on CentOS 6

Due to compatibility limitation, MySQL 5.1, 5.2, 5.3 and 5.5.x must be upgraded to MariaDB 5.5 and cannot be upgraded to MariaDB 10.0 directly. This upgrade plan will walk through getting any one of these deprecated MySQL versions upgraded to MariaDB 5.5.  Once the upgrade to MariaDB 5.5 is complete, follow the How to upgrade MariaDB 5.5 to MariaDB 10.0 on CentOS 6 instructions to continue the upgrade process to MariaDB 10.

Step 1: Confirm backups are present before proceeding at the scheduled time.

Step 2: Stop the MySQL service.

service mysqld stop

Example Output:
~ $ service mysqld restart
Stopping mysqld: [ OK ]

Mysqld has switched to mysql.Step 3: Install the MariaDB 5.5 repository for CentOS 6

cat < /etc/yum.repos.d/MariaDB.repo
[mariadb] name = MariaDB
baseurl = http://yum.mariadb.org/5.5/centos6-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
EOF
This command has no visible output unless errors occur.

Step 4: Clean the yum repository cache

yum clean allExample Output:

~ $ yum clean all
Loaded plugins: fastestmirror
Cleaning repos: base extras mariadb updates
Cleaning up Everything
Cleaning up list of fastest mirrors

Step 5: Remove MySQL packages

yum remove mysql-server mysqlExample Output:

Running Transaction Test
Transaction Test Succeeded
Running Transaction
Erasing : mysql-server-5.1.73-8.el6_8.x86_64 1/1
warning: /var/log/mysqld.log saved as /var/log/mysqld.log.rpmsave
Verifying : mysql-server-5.1.73-8.el6_8.x86_64 1/1
Removed:
mysql-server.x86_64 0:5.1.73-8.el6_8
Complete!
Truncated for brevity.

Step 6: Install the MariaDB-server and MariaDB-client packages via yum.

yum install MariaDB-server MariaDB-client -y

Example Output:Installed:
MariaDB-client.x86_64 0:10.1.35-1.el6 MariaDB-compat.x86_64 0:10.1.35-1.el6 MariaDB-server.x86_64 0:10.1.35-1.el6
Dependency Installed:
MariaDB-common.x86_64 0:10.1.35-1.el6 boost-program-options.x86_64 0:1.41.0-28.el6
galera.x86_64 0:25.3.23-1.rhel6.el6 jemalloc.x86_64 0:3.6.0-1.el6
Replaced:
mysql-libs.x86_64 0:5.1.73-8.el6_8
Complete!
Truncated for brevity.

Step 7: Restart the MySQL service

service mysql startExample Output:

~ $ service mysql start
Starting MariaDB.180808 18:21:13 mysqld_safe Logging to '/var/lib/mysql/cent6.hostname.err'.
180808 18:21:13 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
SUCCESS!
Mysqld has switched to mysql.Step 8: Run MySQL upgrade tool

mysql_upgradeExample Output:

~ $ mysql_upgrade
MySQL upgrade detected
Phase 1/4: Fixing views from mysql
mysql
mysql.columns_priv OK
mysql.db OK
mysql.event OK
mysql.func OK
mysql.time_zone_leap_second OK
mysql.time_zone_name OK
mysql.time_zone_transition OK
mysql.time_zone_transition_type OK
mysql.user OK
Phase 4/4: Running 'mysql_fix_privilege_tables'
OK
Truncated for brevity.

Step 9: Confirm MariaDB server is running as expected

mysql -e 'SHOW VARIABLES LIKE "version"\G'Example Output:

~ $ mysql -e 'SHOW VARIABLES LIKE "version"\G'
*************************** 1. row ***************************
Variable_name: version
Value: 5.5.61-MariaDB

Step 10: The upgrade is complete, check that your databases exist and are working.

[ Optional ] follow the How to upgrade MariaDB 5.5 to MariaDB 10.0 on CentOS 6 instructions.

MariaDB 5.5 to MariaDB 10.0 on CentOS 6

Step 1:  Confirm backups are present before proceeding at the scheduled time.

Step 2: Remove all MariaDB packages.

yum remove MariaDB-*Example Output:
Running Transaction Test
Transaction Test Succeeded
Running Transaction
Erasing : MariaDB-server-5.5.61-1.el6.x86_64 1/2
Erasing : MariaDB-client-5.5.61-1.el6.x86_64 2/2
Verifying : MariaDB-server-5.5.61-1.el6.x86_64 1/2
Verifying : MariaDB-client-5.5.61-1.el6.x86_64 2/2
Removed:
MariaDB-client.x86_64 0:5.5.61-1.el6 MariaDB-server.x86_64 0:5.5.61-1.el6
Complete!
Truncated for brevity.

Step 3: Remove existing MariaDB repository.

rm -f /etc/yum.repos.d/MariaDB*.repoThis command has no visible output unless errors occur.

Step 4: Create MariaDB 10.O Yum repository file.

cat < /etc/yum.repos.d/MariaDB.repo
[mariadb] name = MariaDB
baseurl = http://yum.mariadb.org/10.0/centos6-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
EOF
This command has no visible output unless errors occur.

Step 5: Clean the Yum cache.

yum clean all

Example Output:

~ $ yum clean all
Loaded plugins: fastestmirror
Cleaning repos: base extras mariadb updates
Cleaning up Everything
Cleaning up list of fastest mirrors

Step 6: Install MariaDB-server and MariaDB-client package via Yum.

yum install MariaDB-server MariaDB-clientExample Output:

Running Transaction Test
Transaction Test Succeeded
Running Transaction
Installing : MariaDB-client-10.0.36-1.el6.x86_64 1/2
Installing : MariaDB-server-10.0.36-1.el6.x86_64 2/2
Verifying : MariaDB-server-10.0.36-1.el6.x86_64 1/2
Verifying : MariaDB-client-10.0.36-1.el6.x86_64 2/2
Installed:
MariaDB-client.x86_64 0:10.0.36-1.el6 MariaDB-server.x86_64 0:10.0.36-1.el6
Complete!
Truncated for brevity.

Step 7: Start the MySQL Service.

service mysql start

Step 8: Run the MySQL Upgrade script.

mysql_upgrade

Step 9: The upgrade is complete, check that your databases exist and are working.

 

MySQL 5.1-5.5 to MariaDB 5.5 on Ubuntu 14.04

Step 1:  Confirm backups are present before proceeding at the scheduled time.

Step 2: Install the MariaDB 5.5 repository with this one-liner it’ll install the necessary required tools (if missing), the Ubuntu 14.04 GPG key and the MariaDB 5.5 repository while updating the apt package caches.

sudo apt-get install software-properties-common -y
sudo apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0xcbcb082a1bb943db
sudo add-apt-repository 'deb [arch=amd64,i386,ppc64el] http://ftp.osuosl.org/pub/mariadb/repo/5.5/ubuntu trusty main'
sudo apt-get update

Example Output:
~ $ sudo apt-get install software-properties-common -y > /dev/null
~ $ sudo apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0xcbcb082a1bb943db
Executing: gpg --ignore-time-conflict --no-options --no-default-keyring --homedir /tmp/tmp.PtpHIXMNvY --no-auto-check-trustdb --trust-model always --keyring /etc/apt/trusted.gpg --primary-keyring /etc/apt/trusted.gpg --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0xcbcb082a1bb943db
gpg: requesting key 1BB943DB from hkp server keyserver.ubuntu.com
gpg: key 1BB943DB: public key "MariaDB Package Signing Key <package-signing-key@mariadb.org>" imported
gpg: Total number processed: 1
gpg: imported: 1
~ $ sudo add-apt-repository 'deb [arch=amd64,i386,ppc64el] http://ftp.osuosl.org/pub/mariadb/repo/5.5/ubuntu trusty main'
~ $ sudo apt-get update > /dev/null
Truncated for brevity.

Step 3: Stop mysql service.

sudo service mysql stop
Example Output:
~ $ sudo service mysql stop
mysql stop/waiting

Step 4: Rename MySQL config file /etc/mysql/my.cnf to /etc/mysql/my.cnf.bak. This step is necessary to ensure all incompatible directives/variables have been removed from the configuration to prevent problems with the install.

sudo mv /etc/mysql/my.cnf{,.bak}

Check out incompatible directives.Step 5: Install the mariadb-server package. This will simultaneously remove the existing MySQL binaries and then install the new MariaDB binaries.
sudo apt-get install mariadb-server -y

Example Output:
Example Output: ~ $ sudo apt-get install mariadb-server -y
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
linux-headers-3.13.0-153 linux-headers-3.13.0-153-generic
linux-headers-3.13.0-24 linux-headers-3.13.0-24-generic
linux-headers-3.13.0-91 linux-headers-3.13.0-91-generic
linux-image-3.13.0-153-generic linux-image-3.13.0-24-generic
linux-image-3.13.0-91-generic
Use 'apt-get autoremove' to remove them.
The following extra packages will be installed:
libmariadbclient18 libmysqlclient18 mariadb-client-5.5
mariadb-client-core-5.5 mariadb-common mariadb-server-5.5
mariadb-server-core-5.5
Suggested packages:
tinyca mailx mariadb-test
The following packages will be REMOVED:
mysql-client-5.5 mysql-client-core-5.5 mysql-server mysql-server-5.5
mysql-server-core-5.5
The following NEW packages will be installed:
libmariadbclient18 mariadb-client-5.5 mariadb-client-core-5.5 mariadb-common
mariadb-server mariadb-server-5.5 mariadb-server-core-5.5
The following packages will be upgraded:
libmysqlclient18
1 upgraded, 7 newly installed, 5 to remove and 1 not upgraded.
Need to get 10.4 MB of archives.
After this operation, 22.1 MB of additional disk space will be used.
Get:1 http://ftp.osuosl.org/pub/mariadb/repo/5.5/ubuntu/ trusty/main mariadb-common all 5.5.61+maria-1~trusty [3,180 B] Get:2 http://ftp.osuosl.org/pub/mariadb/repo/5.5/ubuntu/ trusty/main libmysqlclient18 amd64 5.5.61+maria-1~trusty [2,862 B] Get:3 http://ftp.osuosl.org/pub/mariadb/repo/5.5/ubuntu/ trusty/main libmariadbclient18 amd64 5.5.61+maria-1~trusty [521 kB] Get:4 http://ftp.osuosl.org/pub/mariadb/repo/5.5/ubuntu/ trusty/main mariadb-client-core-5.5 amd64 5.5.61+maria-1~trusty [622 kB] Get:5 http://ftp.osuosl.org/pub/mariadb/repo/5.5/ubuntu/ trusty/main mariadb-client-5.5 amd64 5.5.61+maria-1~trusty [961 kB] Get:6 http://ftp.osuosl.org/pub/mariadb/repo/5.5/ubuntu/ trusty/main mariadb-server-core-5.5 amd64 5.5.61+maria-1~trusty [3,831 kB] Get:7 http://ftp.osuosl.org/pub/mariadb/repo/5.5/ubuntu/ trusty/main mariadb-server-5.5 amd64 5.5.61+maria-1~trusty [4,413 kB] Get:8 http://ftp.osuosl.org/pub/mariadb/repo/5.5/ubuntu/ trusty/main mariadb-server all 5.5.61+maria-1~trusty [2,896 B] Fetched 10.4 MB in 1s (7,992 kB/s)
Preconfiguring packages ...
(Reading database ... 165598 files and directories currently installed.)
Removing mysql-server (5.5.61-0ubuntu0.14.04.1) ...
Removing mysql-server-5.5 (5.5.61-0ubuntu0.14.04.1) ...
mysql stop/waiting
Removing mysql-client-5.5 (5.5.61-0ubuntu0.14.04.1) ...
Removing mysql-client-core-5.5 (5.5.61-0ubuntu0.14.04.1) ...
Removing mysql-server-core-5.5 (5.5.61-0ubuntu0.14.04.1) ...
Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
Selecting previously unselected package mariadb-common.
(Reading database ... 165377 files and directories currently installed.)
Preparing to unpack .../mariadb-common_5.5.61+maria-1~trusty_all.deb ...
Unpacking mariadb-common (5.5.61+maria-1~trusty) ...
Preparing to unpack .../libmysqlclient18_5.5.61+maria-1~trusty_amd64.deb ...
Unpacking libmysqlclient18 (5.5.61+maria-1~trusty) over (5.5.61-0ubuntu0.14.04.1) ...
Selecting previously unselected package libmariadbclient18.
Preparing to unpack .../libmariadbclient18_5.5.61+maria-1~trusty_amd64.deb ...
Unpacking libmariadbclient18 (5.5.61+maria-1~trusty) ...
Selecting previously unselected package mariadb-client-core-5.5.
Preparing to unpack .../mariadb-client-core-5.5_5.5.61+maria-1~trusty_amd64.deb ...
Unpacking mariadb-client-core-5.5 (5.5.61+maria-1~trusty) ...
Selecting previously unselected package mariadb-client-5.5.
Preparing to unpack .../mariadb-client-5.5_5.5.61+maria-1~trusty_amd64.deb ...
Unpacking mariadb-client-5.5 (5.5.61+maria-1~trusty) ...
Selecting previously unselected package mariadb-server-core-5.5.
Preparing to unpack .../mariadb-server-core-5.5_5.5.61+maria-1~trusty_amd64.deb ...
Unpacking mariadb-server-core-5.5 (5.5.61+maria-1~trusty) ...
Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
Setting up mariadb-common (5.5.61+maria-1~trusty) ...
Selecting previously unselected package mariadb-server-5.5.
(Reading database ... 165514 files and directories currently installed.)
Preparing to unpack .../mariadb-server-5.5_5.5.61+maria-1~trusty_amd64.deb ...
Unpacking mariadb-server-5.5 (5.5.61+maria-1~trusty) ...
Selecting previously unselected package mariadb-server.
Preparing to unpack .../mariadb-server_5.5.61+maria-1~trusty_all.deb ...
Unpacking mariadb-server (5.5.61+maria-1~trusty) ...
Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
Processing triggers for ureadahead (0.100.0-16) ...
Setting up libmysqlclient18 (5.5.61+maria-1~trusty) ...
Setting up libmariadbclient18 (5.5.61+maria-1~trusty) ...
Setting up mariadb-client-core-5.5 (5.5.61+maria-1~trusty) ...
Setting up mariadb-client-5.5 (5.5.61+maria-1~trusty) ...
Setting up mariadb-server-core-5.5 (5.5.61+maria-1~trusty) ...
Setting up mariadb-server-5.5 (5.5.61+maria-1~trusty) ...
Installing new version of config file /etc/apparmor.d/usr.sbin.mysqld ...
Installing new version of config file /etc/init.d/mysql ...
Installing new version of config file /etc/logrotate.d/mysql-server ...
Installing new version of config file /etc/mysql/debian-start ...
mysql start/running, process 7255
Processing triggers for ureadahead (0.100.0-16) ...
Setting up mariadb-server (5.5.61+maria-1~trusty) ...
Processing triggers for libc-bin (2.19-0ubuntu6.14) ...

Step 6: During the installation an on-screen dialog will appear prompting to change the MySQL root password twice. Follow the instructions to either change the password or skip the change by providing a blank password.

Changing the MySQL root password is advised when upgrading.
Step 7: When completed successfully, the mysql service should automatically start and the mysql_upgrade script is completed automatically during the install process.

A) Check that the mysql service is running.sudo service mysql status
Example Output:
~ $ sudo service mysql status
mysql start/running, process 4745

B) Check that the mysql_upgrade was successful.sudo mysql_upgrade

Example Output:
~ $ sudo mysql_upgrade
This installation of MySQL is already upgraded to 5.5.61-MariaDB, use --force if you still need to run mysql_upgrade

Step 8: The upgrade is complete, check that your databases exist and are working.

MySQL 5.7 to MariaDB 10.2 on Ubuntu 16.04

Step 1:  Confirm backups are present before proceeding at the scheduled time.

Step 2: Check the local root account has a proper password. Before upgrading to MariaDB 10.2, check the ‘root’ @ ’localhost’ user to ensure a password is assigned otherwise, the auth_socket plugin uses an empty password. This is common practice in older setups and causes problems with the upgrade process due to the default mode of MariaDB 10.2 in Strict SQL.

The following script will print the local root user details.

mysql -e 'select User,Host,Plugin,authentication_string from user where authentication_string = "" and plugin = "auth_socket";' mysql
Example Output:
~ $ mysql -e 'select User,Host,Plugin,authentication_string from user where authentication_string = "" and plugin = "auth_socket";' mysql
+------+-----------+-------------+-----------------------+
| User | Host | Plugin | authentication_string |
+------+-----------+-------------+-----------------------+
| root | localhost | auth_socket | |
+------+-----------+-------------+-----------------------+

Below are two examples of how to update these entries.

Automagic Method: The following one-liner reads the password from /root/.my.cnf and uses that password to update the MySQL user entry, if the file exists.

sudo test -e /root/.my.cnf && sudo mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$(awk -F"[=']" 'tolower($1)~/password/{print $(NF-1)}' /root/.my.cnf)'; select User,Host,Plugin,authentication_string from user where user = 'root' and host = 'localhost';" mysql || echo “ERROR: /root/.my.cnf does not exist, are you root?”
Example Output:
~ $ sudo test -e /root/.my.cnf && sudo mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$(awk -F"[=']" 'tolower($1)~/password/{print $(NF-1)}' /root/.my.cnf)'; select User,Host,Plugin,authentication_string from user where user = 'root' and host = 'localhost';" mysql || echo “ERROR: /root/.my.cnf does not exist, are you root?”
+------+-----------+-----------------------+-------------------------------------------+
| User | Host | Plugin | authentication_string |
+------+-----------+-----------------------+-------------------------------------------+
| root | localhost | mysql_native_password | *40C5E49F0CC7BDC637FEEDFBF14FF100C37619D7 |
+------+-----------+-----------------------+-------------------------------------------+
if the Automagic method does not work try the manual method.

Manual Method: The following syntax is necessary to add a proper password to the root user account. Don’t forget to update the /root/.my.cnf file with the correct password or your update may encounter errors. Be sure to substitute the correct password for SuperSecretPass.

ALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘SuperSecretPass’;

Step 3: Install the MariaDB 10.2 repository. This is a multi-command stanza that will install the necessary required tools, GPG key, repository and update the package caches.

sudo apt-get install software-properties-common -y > /dev/null
sudo apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0xF1656F24C74CD1D8
sudo add-apt-repository 'deb [arch=amd64,arm64,i386,ppc64el] http://ftp.osuosl.org/pub/mariadb/repo/10.2/ubuntu xenial main'
sudo apt-get update > /dev/null

Example Output:
~ $ sudo apt-get install software-properties-common -y
~ $ sudo apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0xF1656F24C74CD1D8
Executing: /tmp/tmp.J8PdET9w5B/gpg.1.sh --recv-keys
--keyserver
hkp://keyserver.ubuntu.com:80
0xF1656F24C74CD1D8
gpg: requesting key C74CD1D8 from hkp server keyserver.ubuntu.com
gpg: key C74CD1D8: public key "MariaDB Signing Key <signing-key@mariadb.org>" imported
gpg: Total number processed: 1
gpg: imported: 1 (RSA: 1)
~ $ sudo add-apt-repository 'deb [arch=amd64,arm64,i386,ppc64el] http://ftp.osuosl.org/pub/mariadb/repo/10.2/ubuntu xenial main'
~ $ sudo apt-get update > /dev/null
Truncated for brevity.

Step 4: Stop mysql service.

sudo service mysql stop
Example Output:
~ $ sudo service mysql stop
mysql stop/waiting

Step 5: Rename MySQL config file /etc/mysql/my.cnf to /etc/mysql/my.cnf.bak. This step is necessary to ensure all incompatible directives/variables have been removed from the configuration to prevent problems with the install.
sudo mv /etc/mysql/my.cnf{,.bak}Check out incompatible directives.
Step 6: Install the mariadb-server package. This will simultaneously remove the existing MySQL binaries and then install the new MariaDB binaries.

sudo apt-get install mariadb-server -yExample Output:
~ $ sudo apt install mariadb-server -y</code?

Step 7: During the installation an on-screen dialog will appear prompting that the root password could not be changed because one is already in place. Press enter to proceed.

During upgrading MariaDB will state that a password already exists.

Step 8: When completed successfully, the mysql service should automatically start.
sudo service mysql statusExample Output:
~ $ sudo service mysql status
mysql start/running, process 4745

Step 9: Finally, run mysql_upgrade to complete the upgrade.
sudo mysql_upgradeThe output is suppose illustrates normal errors when upgrading.

Example Output:

~ $ sudo mysql_upgrade
MySQL upgrade detected
Phase 1/7: Checking and upgrading mysql database
Processing databases
mysql
mysql.column_stats OK
mysql.columns_priv OK
mysql.db OK
mysql.engine_cost OK
mysql.event OK
mysql.func OK
mysql.gtid_executed OK
mysql.gtid_slave_pos OK
mysql.help_category OK
mysql.help_keyword OK
mysql.help_relation OK
mysql.help_topic OK
mysql.host OK
mysql.index_stats OK
mysql.innodb_index_stats OK
mysql.innodb_table_stats OK
mysql.plugin OK
mysql.proc OK
mysql.procs_priv OK
mysql.proxies_priv OK
mysql.roles_mapping OK
mysql.server_cost OK
mysql.servers OK
mysql.slave_master_info OK
mysql.slave_relay_log_info OK
mysql.slave_worker_info OK
mysql.table_stats OK
mysql.tables_priv OK
mysql.time_zone OK
mysql.time_zone_leap_second OK
mysql.time_zone_name OK
mysql.time_zone_transition OK
mysql.time_zone_transition_type OK
mysql.user OK
Upgrading from a version before MariaDB-10.1
Phase 2/7: Installing used storage engines
Checking for tables with unknown storage engine
Phase 3/7: Fixing views from mysql
sys.host_summary
Error : Table 'performance_schema.memory_summary_by_host_by_event_name' doesn't exist
Error : View 'sys.host_summary' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.host_summary_by_file_io
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.host_summary_by_file_io_type
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.host_summary_by_stages
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.host_summary_by_statement_latency
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.host_summary_by_statement_type
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.innodb_buffer_stats_by_schema
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.innodb_buffer_stats_by_table
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.innodb_lock_waits
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.io_by_thread_by_latency
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.io_global_by_file_by_bytes
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.io_global_by_file_by_latency
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.io_global_by_wait_by_bytes
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.io_global_by_wait_by_latency
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.latest_file_io
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.memory_by_host_by_current_bytes
Error : Table 'performance_schema.memory_summary_by_host_by_event_name' doesn't exist
Error : View 'sys.memory_by_host_by_current_bytes' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.memory_by_thread_by_current_bytes
Error : Table 'performance_schema.memory_summary_by_thread_by_event_name' doesn't exist
Error : View 'sys.memory_by_thread_by_current_bytes' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.memory_by_user_by_current_bytes
Error : Table 'performance_schema.memory_summary_by_user_by_event_name' doesn't exist
Error : View 'sys.memory_by_user_by_current_bytes' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.memory_global_by_current_bytes
Error : Table 'performance_schema.memory_summary_global_by_event_name' doesn't exist
Error : View 'sys.memory_global_by_current_bytes' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.memory_global_total
Error : Table 'performance_schema.memory_summary_global_by_event_name' doesn't exist
Error : View 'sys.memory_global_total' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.metrics
Error : Table 'performance_schema.global_status' doesn't exist
Error : View 'sys.metrics' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.processlist
Error : Table 'performance_schema.events_transactions_current' doesn't exist
Error : View 'sys.processlist' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.ps_check_lost_instrumentation
Error : Table 'performance_schema.global_status' doesn't exist
Error : View 'sys.ps_check_lost_instrumentation' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.schema_auto_increment_columns OK
sys.schema_index_statistics
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.schema_object_overview OK
sys.schema_redundant_indexes OK
sys.schema_table_lock_waits
Error : Table 'performance_schema.metadata_locks' doesn't exist
Error : View 'sys.schema_table_lock_waits' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.schema_table_statistics
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.schema_table_statistics_with_buffer
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.schema_tables_with_full_table_scans
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.schema_unused_indexes OK
sys.session
Error : Table 'performance_schema.events_transactions_current' doesn't exist
Error : View 'sys.session' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.session_ssl_status
Error : Table 'performance_schema.status_by_thread' doesn't exist
Error : View 'sys.session_ssl_status' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.statement_analysis
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.statements_with_errors_or_warnings
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.statements_with_full_table_scans
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.statements_with_runtimes_in_95th_percentile
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.statements_with_sorting
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.statements_with_temp_tables
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.user_summary
Error : Table 'performance_schema.memory_summary_by_user_by_event_name' doesn't exist
Error : View 'sys.user_summary' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.user_summary_by_file_io
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.user_summary_by_file_io_type
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.user_summary_by_stages
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.user_summary_by_statement_latency
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.user_summary_by_statement_type
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.version OK
sys.wait_classes_global_by_avg_latency
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.wait_classes_global_by_latency
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.waits_by_host_by_latency
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.waits_by_user_by_latency
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.waits_global_by_latency
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.x$host_summary
Error : Table 'performance_schema.memory_summary_by_host_by_event_name' doesn't exist
Error : View 'sys.x$host_summary' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.x$host_summary_by_file_io OK
sys.x$host_summary_by_file_io_type OK
sys.x$host_summary_by_stages OK
sys.x$host_summary_by_statement_latency OK
sys.x$host_summary_by_statement_type OK
sys.x$innodb_buffer_stats_by_schema OK
sys.x$innodb_buffer_stats_by_table OK
sys.x$innodb_lock_waits OK
sys.x$io_by_thread_by_latency OK
sys.x$io_global_by_file_by_bytes OK
sys.x$io_global_by_file_by_latency OK
sys.x$io_global_by_wait_by_bytes OK
sys.x$io_global_by_wait_by_latency OK
sys.x$latest_file_io OK
sys.x$memory_by_host_by_current_bytes
Error : Table 'performance_schema.memory_summary_by_host_by_event_name' doesn't exist
Error : View 'sys.x$memory_by_host_by_current_bytes' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.x$memory_by_thread_by_current_bytes
Error : Table 'performance_schema.memory_summary_by_thread_by_event_name' doesn't exist
Error : View 'sys.x$memory_by_thread_by_current_bytes' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.x$memory_by_user_by_current_bytes
Error : Table 'performance_schema.memory_summary_by_user_by_event_name' doesn't exist
Error : View 'sys.x$memory_by_user_by_current_bytes' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.x$memory_global_by_current_bytes
Error : Table 'performance_schema.memory_summary_global_by_event_name' doesn't exist
Error : View 'sys.x$memory_global_by_current_bytes' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.x$memory_global_total
Error : Table 'performance_schema.memory_summary_global_by_event_name' doesn't exist
Error : View 'sys.x$memory_global_total' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.x$processlist
Error : Table 'performance_schema.events_transactions_current' doesn't exist
Error : View 'sys.x$processlist' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.x$ps_digest_95th_percentile_by_avg_us OK
sys.x$ps_digest_avg_latency_distribution OK
sys.x$ps_schema_table_statistics_io
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.x$schema_flattened_keys OK
sys.x$schema_index_statistics OK
sys.x$schema_table_lock_waits
Error : Table 'performance_schema.metadata_locks' doesn't exist
Error : View 'sys.x$schema_table_lock_waits' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.x$schema_table_statistics
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.x$schema_table_statistics_with_buffer
Error : Cannot load from mysql.proc. The table is probably corrupted
error : Corrupt
sys.x$schema_tables_with_full_table_scans OK
sys.x$session
Error : Table 'performance_schema.events_transactions_current' doesn't exist
Error : View 'sys.x$session' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.x$statement_analysis OK
sys.x$statements_with_errors_or_warnings OK
sys.x$statements_with_full_table_scans OK
sys.x$statements_with_runtimes_in_95th_percentile OK
sys.x$statements_with_sorting OK
sys.x$statements_with_temp_tables OK
sys.x$user_summary
Error : Table 'performance_schema.memory_summary_by_user_by_event_name' doesn't exist
Error : View 'sys.x$user_summary' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
error : Corrupt
sys.x$user_summary_by_file_io OK
sys.x$user_summary_by_file_io_type OK
sys.x$user_summary_by_stages OK
sys.x$user_summary_by_statement_latency OK
sys.x$user_summary_by_statement_type OK
sys.x$wait_classes_global_by_avg_latency OK
sys.x$wait_classes_global_by_latency OK
sys.x$waits_by_host_by_latency OK
sys.x$waits_by_user_by_latency OK
sys.x$waits_global_by_latency OK
Phase 4/7: Running 'mysql_fix_privilege_tables'
Phase 5/7: Fixing table and database names
Phase 6/7: Checking and upgrading tables
Processing databases
information_schema
performance_schema
sys
sys.sys_config OK
Phase 7/7: Running 'FLUSH PRIVILEGES'
OK

performance_schema and mysql.pc are normal errors when updating MySQL.Step 10: The upgrade is complete, check that your databases exist and are working.

MySQL Performance: MySQL vs. MariaDB

MariaDB and MySQL logos.

We continue our series on MySQL Optimization by focusing on the differences and similarities between MariaDB and MySQL. MariaDB is a popular alternative to using traditional MySQL for database hosting. The free market of hosting allows additional actors to compete with the long-standing database solution, MySQL. MariaDB is the most prominent alternative to MySQL and is a favorite among industry giants such as Google, Craigslist, Wikipedia, Arch Linux, RedHat, CentOS, Fedora, and cPanel. In a direct performance comparison, MariaDB leaps to the head of the pack through performance optimizations, easy of conversion and compatibility.

Why Switch to MariaDB?

MariaDB is mostly a clone of MySQL, but it also provides several improvements over running the standard MySQL instance. MariaDB aims for a drop-in replacement to MySQL, which makes the switch painless and straightforward. Combine the simplicity of switching with a long list of improvements, MariaDB brings both performance and cutting-edge features to the table. Below are some of its selling points over standard MySQL.

More Storage Engines Options: There is 12 new storage engine built into MariaDB. Among these are CONNECT, Spider, and SphinxSE. Visit their Storage Engines page for a complete list of these engines, how they function, and ways to leverage them to optimize your database.

Speed improvements: MariaDB sports many new speed improvements compared directly with standard MySQL. This improved performance makes MariaDB stand apart from the baseline performance of traditional MySQL servers. Like MySQL, MariaDB has dozens of features for speed optimization including disk access, JOIN and EXPLAIN improvements, subquery, derived tables/views, execution control, and optimizer control.

Faster Indexes/Cache: When using the MEMORY storage engine, MariaDB can complete INSERT statements up to 24% faster than traditional MySQL servers, along with CHECKSUM TABLE and MyISAM Segment Key Cache being 4x faster.

Speedier and Larger Connection Pool: MariaDB benefits from an improved pool of threads that run faster and support up to 200,000+ connections where standard MySQL falls short.

Improved Replication: MariaDB sports faster and safer replication with updates being up to 2x faster than with traditional MySQL Replication setups. Now possible, parallel replication allows the existence of Active/Active or Master/Master configurations. MariaDB replication is backward compatible with MySQL servers, so migrating your cluster to MariaDB is possible by utilizing one node at a time.

New Extensions/Features: There are several new extension and features, to name a few, the WITH, JSON and KILL statements. DECIMAL sees an increased from 30 to 38 decimals while KILL ALL queries for a specified user.

List of Features: Available MariaDB’s website is a comprehensive list of improvements and features, located here: MariaDB versus MySQL-Features.

 

What is the Downside to Using MariaDB?

The MariaDB project is entirely open-source and free, unlike MySQL which uses dual licensing to keep its Enterprise edition specific features proprietary. The MariaDB developers actively update and enhance with cutting-edge features that standard MySQL does not carry.

Missing Features: MySQL uses some proprietary code in its Enterprise Edition. MariaDB does not have access to this propriety content and is a closed source, meaning the features are only available to MySQL Enterprise users.

Mitigation: MariaDB has addressed this concern through allowing viable open-source alternative plugins for MariaDB, providing the same functionality that the MySQL Enterprise Edition offers. This allows the vast majority of standard MySQL and MySQL Enterprise Edition users the option to switch to MariaDB, taking advantage of its robust performance enhancing features.

Delayed MySQL Compatibility: MariaDB originally forked from MySQL 5.5, so this is the base starting point for the MariaDB source code. Meaning that newer features and bug fixes developed for standard MySQL after version 5.5 are not part of the existing MariaDB source code.

Mitigation: MariaDB conducts monthly merges of the standard MySQL source code to ensure both compatibility and feature/bug-fix adoption. This kind of regular code merging, allows MariaDB to maintain its allure as a drop-in replacement for practically any existing versions of standard MySQL. However, there will always be a delay causing MariaDB to lag behind MySQL’s newer features and bug patches.

MySQL Performance: How To Leverage MySQL Database Indexing

A Mysql Indexing Logo

Throughout this tutorial, we will cover some of the fundamentals of indexing. As part of the MySQL series, we will introduce capabilities of MySQL indexing and the role it plays in optimizing database performance. Liquid Web recommends consulting with a DBA before making any changes to your production level application.

What is Indexing?

Indexing is a powerful structure in MySQL which can be leveraged to get the fastest response times from common queries. MySQL queries achieve efficiency by generating a smaller table, called an index, from a specified column or set of columns. These columns, called a key, can be used to enforce uniqueness. Below is a simple visualization of an example index using two columns as a key.

+------+----------+----------+
| ROW | COLUMN_1 | COLUMN_2 |
+------+----------+----------+
| 1 | data1 | data2 |
+------+----------+----------+
| 2 | data1 | data1 |
+------+----------+----------+
| 3 | data1 | data1 |
+------+----------+----------+
| 4 | data1 | data1 |
+------+----------+----------+
| 5 | data1 | data1 |
+------+----------+----------+

Queries utilize indexes to identify and retrieve the targeted data, even if they are a combination of keys. Without an index, running that same query results in an inspection of every row for the needed data. Indexing produces a shortcut, with much faster query times on expansive tables. A textbooks analogy may provide another common way to visualize how indexes function.
This analogy compares MySQL indexing to indexing in the back of a book.

When to Enable Indexing?

Indexing is only advantageous for huge tables with regularly accessed information. For instance, to continue with our textbook analogy, it makes little sense to index a children’s storybook with only a dozen pages. It’s more efficient to simply read the book to find each occurrence of the word “turtle” than it would be to set up and maintain indexes, query for those indexes, and then review each page provided. In the computing world, those extra tasks surrounding indexing represent wasted resources which would be better purposed by not indexing.

Without indexes, when tables grow to enormous proportions, response times suffer from queries targeting those obtuse tables. Inefficient queries manifest into latency within application or website performance. We commonly identify this latency by using the MySQL slow query log feature. You can find more details about using the slow query log feature in the first article in this series: MySQL Performance: Identifying Long Queries.
Once a colossal table hits its tipping point, it reaches the potential for downtime for applications and websites. Conducting routine evaluations for growing database establishes optimal database performance and sidesteps long queries’ inherent interruptions.

MySQL Indexing Pros vs. Cons

There are benefits and downsides to using MySQL indexing, and we’ll discuss the significant pros and cons for your consideration. These aspects will guide you to decide whether indexing is an appropriate choice for your situation.

quick data transmissions and ideal for OLAP.

What Information Does One Index?

Selecting what to index is probably the most challenging part to indexing your databases. Determining what is important enough to index and what is benign enough to not index. Generally speaking, indexing works best on those columns that are the subject of the WHERE clauses in your commonly executed queries. Consider the following simplified table:

ID, TITLE, LAST_NAME, FIRST_NAME, MAIDEN_NAME, DOB, GENDER, AGE, DESCRIPTION, HISTORY, ETC...

If your queries rely on testing the WHERE clause using LAST_NAME and FIRST_NAME then indexing by these two columns would significantly increase query response times. Alternately, if your queries rely on a simple ID lookup, indexing by ID would be the better choice.

These examples are merely a rudimentary example, and there are several types of indexing structures built-in to MySQL. The following MySQL page discusses these types of indexes in greater detail, and a recommended read for anyone considering indexing: How MySQL Uses Indexes

What is a Unique Index?

Another point for consideration when evaluating which columns to serve as the key in your index is whether to use the UNIQUE constraint. Setting the UNIQUE constraint will enforce uniqueness based on the configured indexing key. As with any key, this can be a single column or a concatenation of multiple columns. The function of this constraint ensures that there are no duplicate entries in the table based on the configured key.

UNIQUE constraints increase write speeds, a taxation of implementation.

What is a Primary Key Index?

As commonly invoked as the UNIQUE constraint the PRIMARY KEY is used to optimize indexes. This constraint ensures that the designated PRIMARY KEY cannot be of a null value. As a result, a performance boost occurs when running on an InnoDB storage engine for the table in question. This boost is due to how InnoDB physically stores data, placing null valued rows in the key out of contiguous sequence with rows that have values. Enabling this constraint ensures the rows of the table are kept in contiguous order for quicker responses.

Primary Key Index is absolutely necessary for large tables.

Managing Indexes

Now we will cover some of the basics of manipulating indexes using MySQL syntax. In examples, we will include the creation, deletion, and listing of indexes.Keywords for Managing Indexes: dbName, tableName, indexName Keep in mind, these examples have placeholder entries for the specific keywords. These keywords are self-explanatory by nature for easy reading, and below is an outline of them.

Instead of tableName you can use dbName.tableName.

Listing/Showing Indexes

Tables can have multiple indexes. Managing indexes will inevitably require being able to list the existing indexes on a table. The syntax for viewing an index is below.

SHOW INDEX FROM tableName;

SHOW INDEX FROM tableName; shows all indexes.

Indexing are present on 3 different columns.

Creating Indexes

Index creation has a simple syntax. The difficulty is in determining what columns need indexing and whether enforcing uniqueness is necessary. Below we will illustrate how to create indexes with and without a PRIMARY KEY and UNIQUE constraints.

As previously mentioned, tables can have multiple indexes. Multiple indexing is useful for creating indexes attuned to the queries required by your application or website. The default settings allow for up to 16 indexes per table, increase this number but is generally more than is necessary. Indexes can be created during a table’s creation or added on to the table as additional indexes later on. We will go over both methods below.

Creating too many indexes can add latency, but if you must then increase buffers in MySQL config.

Example: Create a Table with a Standard Index

CREATE TABLE tableName (
ID int,
LName varchar(255),
FName varchar(255),
DOB varchar(255),
LOC varchar(255),
INDEX ( ID )
);
You can create an index for several columns, using ID as the index.

Example: Create a Table with Unique Index & Primary Key

CREATE TABLE tableName (
ID int,
LName varchar(255),
FName varchar(255),
DOB varchar(255),
LOC varchar(255),
PRIMARY KEY (ID),
UNIQUE INDEX ( ID )
);
You can create an Primary Key and UNIQUE constraint over several columns.

Example: Add an Index to Existing Table

CREATE INDEX indexName ON tableName (ID, LName, FName, LOC);CREATE INDEX statement creates an index and names it.

Example: Add an Index to Existing Table with Primary Key

CREATE UNIQUE INDEX indexName ON tableName (ID, LName, FName, LOC);the CREATE UNIQUE command can add an index to a table ensuring no duplicate data.

Deleting Indexes

While managing indexes, you may find it necessary to remove some. Deleting indexes is also a very simple process, see the example below:

DROP INDEX indexName ON tableName;The DROP INDEX command lets us drop indexes on particular column.

There are many ways to optimize your database for true efficiency. If you would like to learn more or convert the search engines types available in MySQL read through our MyISAM vs. InnoDB tutorial.  Or if you are need of high functioning databases check out our MySQL product page to view different options.

SQL Databases Migration with Command Line

What if you have dozens of SQL databases and manually backing up/restoring each database is too time-consuming for your project? No problem! We can script out a method that will export and import all databases at once without needing manual intervention. For help with transferring SQL Logins and Stored Procedures & Views take a look at our MSSQL Migration with SSMS article.

1. Open SSMS (Microsoft SQL Server Management Studio) on the source server, log in to the SQL instance and open a New Query window. Run the following query:

SELECT name FROM master.sys.databases

This command will output a list of all MSSQL databases on your server. To copy this list out, click anywhere in the results and use the keyboard shortcut CTRL+A (Command + A for Mac users) to select all databases. After highlighting all the databases right click and select copy.

2. Open Notepad, paste in your results and delete all databases (in the newly copied notepad text) you do NOT wish to migrate, as well as deleting the following entries:

  • master
  • tempdb
  • model
  • msdb

These entries are the system’s databases, and copying them is not necessary. Make sure to delete everything except explicitly the databases you need to migrate.  You should now have a list of all required databases separated by a line. i.e.

  • AdventureWorks2012
  • AdventureWorks2014
  • AdventureWorks2016

3. Save this result on the computer as C:\databases.txt.

4. Create a new Notepad window, copy/paste the following into the document and save it as C:\db-backup.bat

mkdir %systemdrive%\dbbackups
for /F "tokens=*" %%a in (databases.txt) do ( sqlcmd.exe -Slocalhost -Q"BACKUP DATABASE %%a TO DISK ='%systemdrive%\dbbackups\%%a.bak' WITH STATS" )

5. Now that you’ve saved the file as C:\db-backup.bat, navigate to the Start menu and type cmd and right click on Command Prompt to select Run as Administrator.Type the following command:

cd C:\

And hit enter. Afterward, type db-backup.bat and hit enter once again.

At this point, your databases have begun exporting and you will see the percentage progress of each databases export (pictured below).

Command line shows the process of each database that is exported.

Take note of any failed databases, as you can re-run the batch file when it’s done, using only the databases that may have failed. If the databases are failing to back up, take note of the error message displayed in the command prompt, address the error by modifying the existing C:\databases.txt file to include only the failed databases and re-run db-backup.bat until all databases are successfully exported.

 

By now you have the folder C:\dbbackups\ that contains .bak files for each database you want to migrate. You will need to copy the folder and your C:\databases.txt file to the destination server. There are numerous ways to move your data to the destination server; you can use USB, Robocopy or FTP. The folder on the C drive of the destination server should be called C:\dbbackups . It’s important to accurately name the file as our script will be looking for the .bak files here. Be sure that the destination server has your C:\databases.txt file as well, as our script will be looking for the database names here.

 

1. Open a Notepad and copy/paste the following into the document and save it as C:\db-restore.bat

for /F "tokens=*" %%a in (C:\databases.txt) do (
sqlcmd.exe -E -Slocalhost -Q"RESTORE DATABASE %%a FROM DISK='%systemdrive%\dbbackups\%%a.bak' WITH RECOVERY"
)

2. Save the file as C:\db-restore.bat 

3. Navigate to the Start menu and type cmd.

4. Right click on Command Prompt and select Run as Administrator. Type the following command:

cd C:\

and hit Enter. Now type db-restore.bat and hit Enter.

Your databases have now begun importing. You will see the percentage of each databases restoration and the message “RESTORE DATABASE successfully processed” for each database that has been successfully processed.

Take note of any failed databases, as you can re-run the batch file when it’s done, using only the databases that have failed. If the databases are failing to back up, take note of the error message displayed in the command prompt, address the error (you can change the batch file as necessary), modify C:\databases.txt to include only the failed databases and re-run db-restore.bat until all databases are successfully exported.

Congratulations, you have now backed up and restored all of your databases to the new server. If you have any login issues while testing the SQL connections on the destination server, refer to the Migrating Microsoft SQL Logins (anchor link) section of this article and follow the steps therein. To migrate views or stored procedures please refer to the Migrating Views and Stored Procedures section. Every SQL server will have it’s own configurations and obstacles to face but we hope this article has given you a strong foundation for your Microsoft SQL Server Migration.

 

SQL Database Migration with SSMS

Migrating MSSQL between servers can be challenging without the proper guidelines to keep you on track. In this article, I will be outlining the various ways to migrate Microsoft SQL Server databases between servers or instances. Whether you need to move a single database,  many databases, logins or stored procedures and views we have you covered!

There are many circumstances where you will need to move a database or restore databases. The most common reasons are:

 

  • Moving to an entirely new server.
  • Moving to a different instance of SQL.
  • Creating a development server or going live to a production server.
  • Restoring databases from a backup.

 

There are two main ways to move SQL databases. Manually with Microsoft SQL Server Management Studio (SSMS) or with the command line. The method you choose depends on what you need to accomplish. If you are moving a single database or just a few, manually backing up and restoring the databases with SSMS will be the easiest approach. If you are moving a lot of databases (think more than 10) then using the command line method will speed up the process. The command line method takes more prep work beforehand, but if you are transferring dozens of databases, then it is well worth the time spent configuring the script instead of migrating each database individually. If you aren’t sure which method to use, try the manual approach first while you get comfortable with the process. I recommend reading all the way through for a deeper understanding of the methodology.

 

Useful References for Terminology

SSMS – An acronym for Microsoft SQL Server Management Studio.

Source Server – The server or instance you are moving databases from or off.

Destination Server – The server or instance you are moving databases to.

 

Moving SQL databases with the manual method can be very easy. It is the preferred process for transferring a few or smaller databases. To follow this part of the guide, you must have MSSQL, and Microsoft SQL Server Management Studio (SSMS) installed.

 

1. Begin by logging into the Source server (the server you are moving databases from or off of). You will want to open Microsoft SQL Server Management Studio by selecting Start > Microsoft SQL Server >  Microsoft SQL Server Management Studio.

2.Log into the SQL server using Windows Authentication or SQL Authentication.

3. Expand the server(in our case SQL01), expand Databases, select the first database you want to move (pictured below).

Select your database within Microsoft SQL Server Management Studio.

4. Right click on your database and select Tasks then click Back Up.

Back up button in Microsoft SQL Server Management Studio.

5. From here you are now at the Back Up Database screen. You can choose a Backup Type such as Full or Differential, make sure the correct database is selected, and set the destination for the SQL backup. For our example, we can leave the Backup Type as Full.

6. Under Backup Type, check the box for “Copy-only backup.” If you are running DPM or another form of server backup, backing up without the Copy-Only flag will cause a break in the backup log chain.

7. You will see a location under Destination for the path of the new backup. Typically you will Remove this entry then Add a new one to select a folder that SQL has read/write access. Adding a new Backup Destination shows a path similar to the following:

C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\

This C:\ path is where your stored database backup is. Note this location for later reference, as this is the default path to stored backups and will have to have proper read/write access for SQL services.

Note:
Advanced users may be comfortable leaving the destination as is, provided the permissions are correct on the output folder.

8. Next, append a filename to the end of this path such as AdventureWorks2012-081418.bak – Be sure to end the filename with the extension .bak and select OKSet the file name with the .bak extension in Microsoft SQL Server Management Studio

10. Once you have pressed OK on the Select Backup Destination prompt, you are ready to back up the database! All you need to do now is hit OK, and the database will begin backing up. You will see a progress bar in the bottom left-hand corner, and when the backup is complete, a window will appear saying ‘The backup of database ‘AdventureWorks2012’ completed successfully.

Navigate to the destination path, noted earlier, (in this case C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\) you will see your newly created file (in this case AdventureWorks2012-081418.bak) – Congratulations! This file is the full export of your database and is ready to be imported to the new server.  If you have more databases, then repeat the steps above for each database you are moving. After copying all database process to the next step of restoring databases to the destination server.

 

You should now have a .bak file of all your databases on the source server. These database files need to be transferred to the destination server. There are numerous ways to move your data to the destination server; you can use USB, Robocopy or FTP. After copying a database you can store it on your destination server,  for our example, we have stored it on the C drive in a folder named C:\dbbackups .

1. Open Microsoft SQL Server Management Studio.

2. Log in to the SQL server using Windows Authentication or SQL Authentication.

3. Expand the server and right click on Databases and select Restore Database.

4. The Restore Database screen looks very similar to the Back Up Database screen.Under Source, you will want to select Device instead of Database. Selecting Device allows you to restore directly from a file. Once you’ve chosen Device, click the browse icon […]

5. Select Add, then navigate to the folder in which your .bak files lives. (In this case, C:\dbbackups).

6. Select the first database .bak you would like to restore and click OK.

Select the .bak file to import your database into the destination server via SSMS.

7. Click OK and now you are ready to import the database. Before importing, let’s take a look at the Options section on the left-hand side. Under Options, you will see other configurations for restoring databases such as Overwrite the Existing Database, Preserve the Replication Settings and Restrict Access to the Restored DatabaseIn this case, we are not replacing an existing database so I will leave all these options unchecked. If you wanted to replace an existing database (for example, the backed up database has newer data than on the destination server or you are replacing a development or production database) then simply select Overwrite the Existing Database.

Note:
Advanced users may be comfortable leaving the destination as is, provided the permissions are correct on the output folder.

8. Clicking OK  begins the restore process as indicated by the popup window that reads ‘Database ‘AdventureWorks2012′ restored successfully.’ You have migrated your database from the source to the destination server.

Repeat this process for each database that you are migrating. You can then update path references in your scripts/application to point to the new server, verify that the migration was successful.

 

After importing your databases if you are unable to connect using your SQL login, you may receive the error ‘Login failed for user ‘example.’ (Microsoft SQL Server, Error: 18456).‘ Because the database is in the Traditional Login and User Model, logins are stored separately in the source server and credentials are not contained within the database itself. From this point on, the destination server can be configured to use the Contained Database User Model which keeps the logins in your database and out of the source server. (You can read more about this here.)Until then, we will have to move and interact with the users as part of the Traditional model. Continue below to proceed with the migration of your SQL users.

Backing up and restoring the databases did move your SQL logins relation to the databases (your logins are still associated with the correct databases with the correct permissions) but the actual logins itself did not transfer to the new server.  You can verify this by opening SSMS on the destination server and navigating to Server > Security > Logins. You will notice that any custom SQL logins you created on the previous server did not transfer over here, but if you go to Server > Databases > Your Database (AdventureWorks2012 in this case) > Security > Users you’ll see the correct login associated with the database.

If you have one or two SQL users, you can just delete the user’s association to the database in Servers > Databases > AdventureWorks2012 > Security > Users, re-create the user in Server > Security > Logins and map it to the proper database.

If you have a lot of logins, you will have to follow an additional process outlined below. To migrate all SQL users, open a New Query window on the source server and run the following script:

SQL Login Script
USE master
GO
IF OBJECT_ID ('sp_hexadecimal') IS NOT NULL
DROP PROCEDURE sp_hexadecimal
GO
CREATE PROCEDURE sp_hexadecimal
@binvalue varbinary(256),
@hexvalue varchar (514) OUTPUT
AS
DECLARE @charvalue varchar (514)
DECLARE @i int
DECLARE @length int
DECLARE @hexstring char(16)
SELECT @charvalue = '0x'
SELECT @i = 1
SELECT @length = DATALENGTH (@binvalue)
SELECT @hexstring = '0123456789ABCDEF'
WHILE (@i <= @length)
BEGIN
DECLARE @tempint int
DECLARE @firstint int
DECLARE @secondint int
SELECT @tempint = CONVERT(int, SUBSTRING(@binvalue,@i,1))
SELECT @firstint = FLOOR(@tempint/16)
SELECT @secondint = @tempint - (@firstint*16)
SELECT @charvalue = @charvalue +
SUBSTRING(@hexstring, @firstint+1, 1) +
SUBSTRING(@hexstring, @secondint+1, 1)
SELECT @i = @i + 1
END
SELECT @hexvalue = @charvalue
GO
IF OBJECT_ID ('sp_help_revlogin') IS NOT NULL
DROP PROCEDURE sp_help_revlogin
GO
CREATE PROCEDURE sp_help_revlogin @login_name sysname = NULL AS
DECLARE @name sysname
DECLARE @type varchar (1)
DECLARE @hasaccess int
DECLARE @denylogin int
DECLARE @is_disabled int
DECLARE @PWD_varbinary varbinary (256)
DECLARE @PWD_string varchar (514)
DECLARE @SID_varbinary varbinary (85)
DECLARE @SID_string varchar (514)
DECLARE @tmpstr varchar (1024)
DECLARE @is_policy_checked varchar (3)
DECLARE @is_expiration_checked varchar (3)
DECLARE @defaultdb sysname
IF (@login_name IS NULL)
DECLARE login_curs CURSOR FOR
SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM
sys.server_principals p LEFT JOIN sys.syslogins l
ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name <> 'sa'
ELSE
DECLARE login_curs CURSOR FOR
SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM
sys.server_principals p LEFT JOIN sys.syslogins l
ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name = @login_name
OPEN login_curs
FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
IF (@@fetch_status = -1)
BEGIN
PRINT 'No login(s) found.'
CLOSE login_curs
DEALLOCATE login_curs
RETURN -1
END
SET @tmpstr = '/* sp_help_revlogin script '
PRINT @tmpstr
SET @tmpstr = '** Generated ' + CONVERT (varchar, GETDATE()) + ' on ' + @@SERVERNAME + ' */'
PRINT @tmpstr
PRINT ''
WHILE (@@fetch_status <> -1)
BEGIN
IF (@@fetch_status <> -2)
BEGIN
PRINT ''
SET @tmpstr = '-- Login: ' + @name
PRINT @tmpstr
IF (@type IN ( 'G', 'U'))
BEGIN -- NT authenticated account/group
SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' FROM WINDOWS WITH DEFAULT_DATABASE = [' + @defaultdb + ']'
END
ELSE BEGIN -- SQL Server authentication
-- obtain password and sid
SET @PWD_varbinary = CAST( LOGINPROPERTY( @name, 'PasswordHash' ) AS varbinary (256) )
EXEC sp_hexadecimal @PWD_varbinary, @PWD_string OUT
EXEC sp_hexadecimal @SID_varbinary,@SID_string OUT
-- obtain password policy state
SELECT @is_policy_checked = CASE is_policy_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name
SELECT @is_expiration_checked = CASE is_expiration_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name
SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' WITH PASSWORD = ' + @PWD_string + ' HASHED, SID = ' + @SID_string + ', DEFAULT_DATABASE = [' + @defaultdb + ']'
IF ( @is_policy_checked IS NOT NULL )
BEGIN
SET @tmpstr = @tmpstr + ', CHECK_POLICY = ' + @is_policy_checked
END
IF ( @is_expiration_checked IS NOT NULL )
BEGIN
SET @tmpstr = @tmpstr + ', CHECK_EXPIRATION = ' + @is_expiration_checked
END
END
IF (@denylogin = 1)
BEGIN -- login is denied access
SET @tmpstr = @tmpstr + '; DENY CONNECT SQL TO ' + QUOTENAME( @name )
END
ELSE IF (@hasaccess = 0)
BEGIN -- login exists but does not have access
SET @tmpstr = @tmpstr + '; REVOKE CONNECT SQL TO ' + QUOTENAME( @name )
END
IF (@is_disabled = 1)
BEGIN -- login is disabled
SET @tmpstr = @tmpstr + '; ALTER LOGIN ' + QUOTENAME( @name ) + ' DISABLE'
END
PRINT @tmpstr
END
FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
END
CLOSE login_curs
DEALLOCATE login_curs
RETURN 0
GO

This script creates two stored procedures in the source database which helps with migrating these logins. Open a New Query window and run the following:
EXEC sp_help_revlogin

This query outputs a script that creates new logins for the destination server. Copy the output of this query and save it for later. You will need to run this on the destination server.

Once you’ve copied the output of this query, login to SSMS on the destination server and open a New Query window. Paste the contents from the previous script (it should have a series of lines that look similar to — Login: BUILTIN\Administrators
CREATE LOGIN [BUILTIN\Administrators] FROM WINDOWS WITH DEFAULT_DATABASE = [master]) and hit Execute.

You have now successfully imported all SQL logins and can now verify that the databases have been migrated to the destination server by using your previous credentials.

Views and stored procedures will migrate with the database if you are using the typical SQL Tape backups. Follow the instructions below if you need to migrate views and stored procedures independently.

  1. Open Microsoft SQL Management Studio on the Source server.
  2. Log in to your SQL server.
  3. Expand the server and as well as Databases.
  4. Right click on the name of your database and go to Tasks > Generate Scripts.
  5. Click Next.
  6. We will change Script entire database and all database objects to Select specific database objects and only check Views and Stored Procedures.Transfer Stored Procedures and Views within Microsoft SQL Server Management Studio
  7. Click Next, notice the Save to File option. Take note of the file path listed. In my case, it is C:\Users\Administrator\Documents\script.sql – The path of saved views and stored procedures.
  8. Click Next >> Next >>Finish, and select C:\Users\Administrator\Documents\script.sql and copy it to the destination server.
  9. Go to the destination server, open SSMS and log in to the SQL server.
  10. Go to File > Open > File or use the keyboard shortcut CTRL+O to open the SQL script. Select the file C:\Users\Administrator\Documents\script.sql to open it.
  11. You will see the script generated from the source server containing all views and stored procedures. Click Execute or use the keyboard shortcut F5 and run the script.
Note:
Unfortunately, there is no built-in way to do this with the command line. There are 3rd party tools and even a tool by Microsoft called mssql-scripter for more advanced scripting.

You have now migrated the views and stored procedures to your destination server! Repeat this process for each database you are migrating. A little guidance goes a long way in database administration. Every SQL server will have it’s own configurations and obstacles to face but we hope this article has given you a strong foundation for your Microsoft SQL Server Migration.

Looking for a High Availability, platform-independent SQL service that is easily scalable and can grow with your business? Check out our SQL as a Service product offered at Liquid Web. Speak with one of our amazing Hosting Advisers to find the perfect solution for you!

 

Install Memcached on Ubuntu 16.04

Memcached works to enhance performance by keeping a copy of commonly used script elements within the server’s memory in a form that is more easily read by the server thus reducing time. A bonus feature of this object cacher is its ability to decrease the number of connections to your database. In this tutorial, we instruct how to install Memcached, but it’s important to note that when using Memcache in an application, the application must be specially coded or configured to store and retrieve data this cached data.

Learn more about caching from our dedicated article or visit our series for database optimization.

Pre-flight

  • We are logged in as root on an Ubuntu 16.04 VPS powered by Liquid Web!
  • Installed and running Apache and PHP 7.

Installation of Memcached

Step 1:
Following best practices, we will do a quick package update by using the following command:
apt-get update
Step 2:
Install the Memcached daemon using
apt-get install memcached -y
Step 3:
Install the Memcache module for PHP fuctionality:
apt-get install php-memcached -y

Verify installation of Memcached

Use the php -m flag to show compiled modules while sorting through specifically looking for memcached.

php -m | grep memcached
memcached

Optional Configurations

At some point, you may find that you need to change the default settings of Memcached. These include adjusting the port number, memory for your cache, and the listening IP address.
vim /etc/memcached.conf

Adjust these configurations by keeping the same flags (-m, -p, -u, -l), adjusting the letter or number after the flag and save the file by typing :wq .
# Start with a cap of 64 megs of memory. It's reasonable, and the daemon default
# Note that the daemon will grow to this size, but does not start out holding this much
# memory
-m 64
 
# Default connection port is 11211
-p 11211
 
# Run the daemon as root. The start-memcached will default to running as root if no
# -u command is present in this config file
-u memcache
 
# Specify which IP address to listen on. The default is to listen on all IP addresses
# This parameter is one of the only security measures that memcached has, so make sure
# it's listening on a firewalled interface.
-l 127.0.0.1

 

Restart your Memcached service to recognize the changes to this file:
systemctl restart memcached

MySQL Performance: MyISAM vs InnoDB

 

A major factor in database performance is the storage engine used by the database, and more specifically, its tables. Different storage engines provide better performance in one situation over another. For general use, there are two contenders to be considered. These are MyISAM, which is the default MySQL storage engine, or InnoDB, which is an alternative engine built-in to MySQL intended for high-performance databases. Before we can understand the difference between the two storage engines, we need to understand the term “locking.”

To protect the integrity of the data stored within databases, MySQL employs locking. Locking, simply put, means protecting data from being accessed. When a lock is applied, the data cannot be modified except by the query that initiated the lock. Locking is a necessary component to ensure the accuracy of the stored information.  Each storage engine has a different method of locking used. Depending on your data and query practices, one engine can outperform another. In this series, we will look at the two most common types of locking employed by our two storage engines.

 

Table locking:  The technique of locking an entire table when one or more cells within the table need to be updated or deleted. Table locking is the default method employed by the default storage engine, MyISAM.

Example: MyISAM Table LockingColumn AColumn BColumn C
Query 1 UPDATERow 1Writingdatadata
Query 2 SELECT (Wait)Row 2datadatadata
Query 3 UPDATE (Wait)Row 3datadatadata
Query 4 SELECT (Wait)Row 4datadatadata
Query 5 SELECT (Wait)Row 5datadatadata
The example illustrates how a single write operation locks the entire table causing other queries to wait for the UPDATE query finish.

 

Row-level locking: The act of locking an effective range of rows in a table while one or more cells within the range are modified or deleted. Row-level locking is the method used by the InnoDB storage engine and is intended for high-performance databases.

Example: InnoDB Row-Level LockingColumn AColumn AColumn A
Query 1 UPDATERow 1Writingdatadata
Query 2 SELECTRow 2Readingdatadata
Query 3 UPDATERow 3dataWritingdata
Query 4 SELECTRow 4ReadingReadingReading
Query 5 SELECTRow 5ReadingdataReading
The example shows how using row-level locking allows for multiple queries to run on individual rows by locking only the rows being updated instead of the entire table.

 

By comparing the two storage engines, we get to the crux of the argument between using InnoDB over MyISAM. An application or website that has a frequently used table works exceptionally well using the InnoDB storage engine by resolving table-locking bottlenecks. However, the question of using one over the other is a subjective as neither of them is perfect in all situations. There are strengths and limitations to both storage engines. Intimate knowledge of the database structure and query practices is critical for selecting the best storage engine for your tables.

MyISAM will out-perform InnoDB on large tables that require vastly more read activity versus write activity. MyISAM’s readabilities outshine InnoDB because locking the entire table is quicker than figuring out which rows are locked in the table. The more information in the table, the more time it takes InnoDB to figure out which ones are not accessible. If your application relies on huge tables that do not change data frequently, then MyISAM will out-perform InnoDB.  Conversely, InnoDB outperforms MyISAM when data within the table changes frequently. Table changes write data more than reading data per second. In these situations, InnoDB can keep up with large amounts of requests easier than locking the entire table for each one.

 

Should I use InnoDB with WordPress, Magento or Joomla Sites?

The short answer here is yes, in most cases. Liquid Web’s Most Helpful Humans in Hosting Support Teams have encountered several table-locking bottlenecks when clients are using some of the standard web applications of today. Most users of popular third-party applications like WordPress, Magento, and Joomla have limited knowledge of the underlying database components or code involved to make an informed decision on storage engines. Most table-locking bottlenecks from these content management systems (CMS) are generally resolved by changing all the tables for the site over to  InnoDB instead of the default MyISAM.  If you are hosting many of these types of CMS on your server, it would be beneficial to change the default storage engine in MySQL to use InnoDB for all new tables so that any new table installations start off with InnoDB.

 

Set your default storage engine to InnoDB by adding default_storage_engine=InnoDB to the [mysqld] section of the system config file located at:  /etc/my.cnf . Restarting the MySQL service is necessary for the server to detect changes to the file.

~ $ cat /etc/my.cnf
[mysqld]
log-error=/var/lib/mysql/mysql.err
innodb_file_per_table=1
default-storage-engine=innodb
innodb_buffer_pool_size=128M

 

Unfortunately, MySQL does not inherently have an option to convert tables, leaving each table to be changed individually. Liquid Web’s support team has put together an easy to follow maintenance plan for this process. The script, which you can run on the necessary server via shell access (SSH) will convert all tables between storage engines.

Note
Plan accordingly when performing batch operations of this nature just in case downtime occurs. Best practice is to backup all your MySQL Databases before implementing a change of this magnitude, doing so provides an easy recovery point to prevent any data loss.

Step 1: Prep

Plan to start at a time of day where downtime would have minimal consequences. This process itself does not require any downtime, however, downtime may be necessary to recover from unforeseen circumstances.  

 

Step 2: Backup All Databases To A File

The command below creates a single file backup of all databases named all-databases-backup.sqld and can be deleted once the conversion has succeeded and there are no apparent problems.
mysqldump --all-databases > all-databases-backup.sql

 

Step 3: Record Existing Table Engines To A File

Run the following script to record the existing table engines to a file named table-engine-backup.sql. You can then “import” or “run” this file later to convert back to their original engines if necessary.

mysql -Bse 'SELECT CONCAT("ALTER TABLE ",table_schema,".",table_name," ENGINE=",Engine,";") FROM information_schema.tables WHERE table_schema NOT IN("mysql","information_schema","performance_schema");' | tee table-engine-backup.sql

If you need to revert the table engines back for any reason, run:
mysql < table-engine-backup.sql

 

Step 4a: Convert MyISAM Tables To InnoDB

The below command will proceed even if a table fails and lets you know which tables failed to convert. The output is saved to the file named convert-to-innodb.log for later review.
mysql -Bse 'SELECT CONCAT("ALTER TABLE ",table_schema,".",table_name," ENGINE=InnoDB;") FROM information_schema.tables WHERE table_schema NOT IN ("mysql","information_schema","performance_schema") AND Engine = "MyISAM";' | while read -r i; do echo $i; mysql -e "$i"; done | tee convert-to-innodb.log

 

Step 4b: Convert All InnoDB Tables To MyISAM

This command will proceed even if a table fails and lets you know which tables failed to convert. The output is also saved to the file named convert-to-myisam.log for later review.

mysql -Bse 'SELECT CONCAT("ALTER TABLE ",table_schema,".",table_name," ENGINE=MyISAM;") FROM information_schema.tables WHERE table_schema NOT IN ("mysql","information_schema","performance_schema") AND Engine = "InnoDB";' | while read -r i; do echo $i; mysql -e "$i"; done | tee convert-to-myisam.log

 

The following commands illustrate how converting a single table is accomplished.

Note
Replace database_name with the proper database name and table_name with the correct table name. Make sure you have a valid backup of the table in question before proceeding. 

Backup A Single Table To A File
mysqldump database_name table_name > backup-table_name.sql

 

Convert A Single Table To InnoDB

mysql -Bse ‘ALTER TABLE database_name.table_name ENGINE=InnoDB;’

 

Convert A Single Table To MyISAM:

mysql -Bse ‘ALTER TABLE database_name.table_name ENGINE=MyISAM;’

 

Check out our other articles in this series, MySQL Performance: Identifying Long Queries, to pinpoint slow queries within your database.  Stay tuned for our next article where we will cover caching and optimization.

MySQL Performance: Identifying Long Queries

Every MySQL backed application can benefit from a finely tuned database server. The Liquid Web Heroic Support team has encountered numerous situations over the years where some minor adjustments have made a world of difference in website and application performance. In this series of articles, we have outlined some of the more common recommendations that have had the largest impact on performance.

Preflight Check

This article applies to most Linux based MySQL servers. This includes, but is not limited to, both Traditional Dedicated and Cloud VPS servers running a variety of common Linux distributions. The article can be used with the following Liquid Web system types:

  • Core-managed CentOS 6x/7x
  • Core-managed Ubuntu 14.04/16.04
  • Fully-managed CentOS 6/7 cPanel
  • Fully-managed CentOS 7 Plesk Onyx 17
  • Self-managed Linux servers
Note
Self-managed systems, which have opted out of direct support can take advantage of the techniques discussed here, however, the Liquid Web Heroic Support Team cannot offer direct aid on these server types.

This series of articles assumes familiarity with the following basic system administration concepts:

 

What is MySQL Optimization?

There is no clearly defined definition for the term MySQL Optimization. It can mean something different depending on the person,  administrator, group or company. For the sake of this series of articles on MySQL Optimization, we will define MySQL Optimization as:  The configuration of a MySQL or MariaDB server which has been configured to avoid commonly encountered bottlenecks discussed in this series of articles.

What is a bottleneck?

Very similar to the neck on a soda bottle, a bottleneck as a technical term is a point in an application or server configuration where a small amount of traffic or data can pass through without issue. However, a larger volume of the same type of traffic or data is hindered or blocked and cannot operate successfully as-is. See the following example of a configuration bottleneck:

Visual Difference between Optimized and Non-Optimized DatabaseIn this example, the server is capable of handling 10 connections simultaneously. However, the configuration only accepts 5 connections. This issue would not manifest so long as there were 5 or less connections at one time. However, when traffic ramps up to 10 connections, half of them start to fail due to unused resources in the server configuration. The above examples illustrates the bottleneck shape where it derives its name versus an optimized configuration which corrects the bottleneck.

When Should I Optimize My MySQL database?

Ideally, database performance tuning should occur regularly and before productivity is affected. It is best practice behavior to conduct weekly or monthly audits of database performance to prevent issues from adversely affecting  applications. The most obvious symptoms of performance problems are:

  • Queries stack up and never completing in the MySQL process table.
  • Applications or websites using the database become sluggish.
  • Connection timeouts errors, especially during peak hours.

While it is normal for there to be several concurrent queries running at one time on a busy system, it becomes a problem when these queries are taking too long to finish on a regular basis. Although the specific threshold varies per system and per application, average query times exceeding several seconds will manifest as a slowdown within attached websites and applications. These slowdowns can sometimes start out small and go unnoticed until a large traffic surge hits a particular bottleneck.

Identifying Performance Issues

Knowing how to examine the MySQL process table is vital for diagnosing the specific bottleneck being encountered. There is a number of ways to view the process table depending on your particular server and preference. For the sake of brevity this series will focus on the most common methods used via Secure Shell (SSH) access:

 

Using The MySQL Process Table: Method 1

Use the ‘mysqladmin’ command line tool with the flag ‘processlist’ or ‘proc’ for short. (Adding the flag ‘statistics’ or ‘stat’ for short will show running statistics for queries since MySQL’s last restart.)

Command:

mysqladmin proc stat

Output:

 +-------+------+-----------+-----------+---------+------+-------+
| Id | User | Host | db | Command | Time | State | Info | Progress |
+-------+------+-----------+-----------+---------+------+-------+--------------------+----------+
| 77255 | root | localhost | employees | Query | 150 | | call While_Loop2() | 0.000 |
| 77285 | root | localhost | | Query | 0 | init | show processlist | 0.000 |
+-------+------+-----------+-----------+---------+------+-------+--------------------+----------+
Uptime: 861755 Threads: 2 Questions: 20961045 Slow queries: 0 Opens: 2976 Flush tables: 1 Open tables: 1011 Queries per second avg: 24.323

Pro: Used on the shell interface, this makes piping output to other scripts and tools very easy.
Con: The process table’s info column is always truncated so does not provide the full query on longer queries.

Using The MySQL Process Table: Method 2

Run the ‘show processlist;’ query from within MySQL interactive mode prompt. (Adding the ‘full’  modifier to the command disables truncation of the Info column. This is necessary when viewing long queries.)

 

Command:

show processlist;

Output:
MariaDB [(none)]> show full processlist;
+-------+------+-----------+-----------+---------+------+-------+-----------------------+----------+
| Id | User | Host | db | Command | Time | State | Info | Progress |
+-------+------+-----------+-----------+---------+------+-------+-----------------------+----------+
| 77006 | root | localhost | employees | Query | 151 | NULL | call While_Loop2() | 0.000 |
| 77021 | root | localhost | NULL | Query | 0 | init | show full processlist | 0.000 |
+-------+------+-----------+-----------+---------+------+-------+-----------------------+----------+

Pro: Using the full modifier allows for seeing the full query on longer queries.
Con: MySQL Interactive mode cannot access scripts and tools available in the shell interface.

Using The slow query log

Another valuable tool in  MySQL is the included slow query logging feature. This feature is the preferred method for finding long running queries on a regular basis. There are several directives available to adjust this feature. However, the most commonly needed settings are:

 

slow_query_logenable/disable the slow query log
slow_query_log_filename and path of the slow query log file
long_query_timetime in seconds/microseconds defining a slow query

These directives are set within the [mysqld] section of the MySQL configuration file located at /etc/my.cnf and will require a MySQL service restart before they will take affect. See the example below for formatting:

Caution
There is a large disk space concern with the slow query log file, which needs to be attended to continually until the slow query log feature is disabled. Keep in mind, the lower your long_query_time directive the faster the slow query log fills up a disk partition.
[mysqld]
log-error=/var/lib/mysql/mysql.err
innodb_file_per_table=1
default-storage-engine=innodb
innodb_buffer_pool_size=128M
innodb_log_file_size=128M
max_connections=300
key_buffer_size = 8M
slow_query_log=1
slow_query_log_file=/var/lib/mysql/slowquery.log
long_query_time=5

Once the slow query log is enabled you will need to periodically follow-up with it to review unruly queries that need to be adjusted for better performance. To analyze the slow query log file, you can parse it directly to review its contents. The following example shows the statistics for the sample query which ran longer that the configured 5 seconds:

Caution
There is a performance hit taken by enabling the slow query log feature. This is due to the additional routines needed to analyze each query as well as the I/O needed to write the necessary queries to the log file. Because of this, it is considered best practice on production systems to disable the slow query log. The slow query log should only remain enabled for a specific duration when actively looking for troublesome queries that may be impacting the application or website.
# Time: 180717 0:23:28
# User@Host: root[root] @ localhost [] # Thread_id: 32 Schema: employees QC_hit: No
# Query_time: 627.163085 Lock_time: 0.000021 Rows_sent: 0 Rows_examined: 0
# Rows_affected: 0
use employees;
SET timestamp=1531801408;
call While_Loop2();

Optionally, you can use the mysqldumpslow command line tool, which parses the slow query log file and groups like queries together except values of number and string data:
~ $ mysqldumpslow -a /var/lib/mysql/slowquery.log
Reading mysql slow query log from /var/lib/mysql/slowquery.log
Count: 2 Time=316.67s (633s) Lock=0.00s (0s) Rows_sent=0.5 (1), Rows_examined=0.0 (0), Rows_affected=0.0 (0), root[root]@localhost
call While_Loop2()
(For usage information visit MySQL documentation here: mysqldumpslow – Summarize Slow Query Log Files)

So concludes the first part of our Database Optimization series and gives us a solid basis to refer back to for benchmark purposes. Though database issues can be complicated, our series will break down these concepts to provide means to optimize your database through database conversion, table conversion, and indexing.