MySQL & Pivot functionality

Recently whilst writing some code I needed to pivot rows to columns in a MySQL results set. Now with some other DB providers this is standard functionality. Oracle (of which I have previous experience of implementing pivot with), PostgreSQL and MS SQLServer all provide this. Unfortunately MySQL in it’s ultimate wisdom has never implemented this feature. This lead to one of two possibilities:

  1. Implement two separate queries and combine the results together in a PHP foreach loop
  2. As it supports them, a MySQL Stored Procedure

The first option was obviously not preferable, it’s far slower than getting the database to do the work. This lead to the second being my obvious preferred option. My main experience of writing stored procedures and functions in SQL is using PL/SQL with an Oracle DB. I have in general used MySQL on much lighter systems, however have in the odd situation required a stored procedure, so thought why not. The solution was to use a cursor in the stored procedure looping through said cursor to generate a SQL statement, then executing that as a prepared statement to return the results set required. This is then called from PHP by using the MySQL “CALL” functionality.

Here’s an example of the stored procedure I produced:

DROP PROCEDURE IF EXISTS pivot_user_preferences;

DELIMITER $$

CREATE PROCEDURE pivot_user_preferences(IN user_id INT)
BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE definition_label CHAR(255);
    DECLARE label_cursor CURSOR FOR SELECT DISTINCT label FROM example_db.user_preferences;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    SET @user_id = user_id;
    SET @sql_statement = 'SELECT u.* ';

    OPEN label_cursor;

    read_loop: LOOP
        FETCH label_cursor INTO definition_label;
        IF done THEN
            LEAVE read_loop;
        END IF;
        SET @sql_statement = CONCAT(@sql_statement, ', GROUP_CONCAT(IF(up.label = \'', definition_label, '\', up.value, NULL)) AS ', definition_label);
    END LOOP;

    CLOSE label_cursor;

    SET @sql_statement = CONCAT(@sql_statement, ' FROM users u LEFT JOIN user_preferences up ON u.id = up.user_id WHERE u.id = (?) GROUP BY id');
    PREPARE stmt FROM @sql_statement;
    EXECUTE stmt USING @user_id;
    DEALLOCATE PREPARE stmt;
END $$

DELIMITER ;

PHP MySQL PDO and the Multiple Queries Bug

Whilst running multiple queries in one call, via the PHP MySQL PDO driver, I noticed that although PDO was behaving as if all the queries had executed successfully, the entries in the database weren’t all appearing that should have. Obviously something was happening that wasn’t being reported. PDO was setup to throw Exceptions on any errors when the SQL executed so there was clearly a bug somewhere.

Unfortunately it’s a bug in PHP and it seems this bug has existed since at-least April 2012: https://bugs.php.net/bug.php?id=61613

I had three choices:

  1. manually split the queries up into different statements and replace the bind variables with their relevant values (which wasn’t feasible as there were hundreds),
  2. Use str_replace to replace the bind_variables with their relevant quoted values and run the query at the sql prompt (not real world situation due to null values etc.).
  3. Write some code to split the statement into individual queries and  execute said queries individually with the relevant bind variables.

The following is a full example of how to split a long string of multiple sql queries and the relevant bind variables for that query into their separate sections, and execute them one at a time:

<?php
$myConn = new PDO(
	'mysql:host=localhost;dbname=dbname',
	'username',
	'password'
);
$myConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$multiSqlStatement = '
INSERT INTO users (username) VALUES (:username);
INSERT INTO groups (name, type) VALUES (:group_name, :group_type);
INSERT INTO logs (entry) VALUES (NOW());
';
$bindVariables = array(
	':group_type' => 'this_type',
	':username' => 'my_username',
	':group_name' => 'Other'
);

$tempSql = preg_replace('/[\n\r\s]+/', ' ', $multiSqlStatement);
$tempSqlParts = explode(';', $tempSql);
foreach ($tempSqlParts as $tempSqlPart) {
    $tempSqlPart = trim($tempSqlPart);
    if (!empty($tempSqlPart)) {
        $tempBindVars = (0 < preg_match_all('/\:[a-z0-9_]+/i', $tempSqlPart, $matches))
        	? array_intersect_key($bindVariables, array_flip($matches[0]))
        	: array();
        $tempStatement = $myConn->prepareStatement($tempSqlPart);
        $tempStatement->execute($tempBindVars);
        $tempStatement->closeCursor();
    }
}

CloudFlare and Dynamic DNS

Recently I changed ISPs.  This generally isn’t a big deal. It didn’t cause any difference in speed or  connection reliability, however my old ISP had, regardless of me not ordering one, given me a static IP address.  I’d taken advantage of this and assigned the IP to a DNS record to give me easy to remember access to my files when I’m away from home.  Anyway when I changed ISPs I discovered my new one changed my IP address every few days, which is an unfortunate thing to discover when you’re not at home.

I took a look at my router and found it only supported DynDns, which I then found out that, apart from to some DLink users, didn’t provide provide a free version of their service to the general public, and I don’t have a DLink router.

The next option was a free alternative to DynDns, there were several, and they all required running some kind of linux demon / cron script, which I would then have to alter my existing A record DNS entry to a CNAME to point to the new dynamic DNS record.

Before setting this up I thought I’d look into my existing DNS provider just incase there was any way of updating DNS records on the fly without having to maintain two separate DNS providers. I found that CloudFlare had an API, which I could update records with. The example provided was a Curl example, which made me wonder, surely I could just write a bash script to update the record with via a cron job. I didn’t want to have to install any major scripting language on my minimal Linux distro, excluding any php, perl etc. solution I’d found that worked with CloudFlare.

I checked CloudFlare’s API rate limiting and found it certainly wouldn’t be limiting for what I was trying to do (it’s approximately 1200 requests every 5 mins if you’re wondering). I then found MyExternalIP that could provide my external IP address with a rate limit that was easy to deal with of roughly 1/s, after which it was just a case of writing the bash script.

I worked a script out using Curl requests to get the information I needed including the specific id of the DNS record I was trying to update and then used sed to get the information I needed out each requests response. I made it compatible with the CloudFlareAPI call I was making that way any parameter passed to the call could be passed by a command line argument to the script itself.

The resultant script I added to my crontab to run every half hour.  Everything worked perfectly so I thought  I’d create a gist at github so others could take advantage of this:

#!/bin/sh
#
# CloudFlare Dynamic DNS
#
# Updates CloudFlare records with the current public IP address
#
# Takes the same basic arguments as A/CNAME updates in the CloudFlare v4 API
# https://www.cloudflare.com/docs/client-api.html#s5.2
#
# Use with cron jobs etc.
#
# e.g.
#
# manually run:
# cloudflare_dyn_dns.sh -key 404613183ab3971a2118ae5bf03d63e032f9e -email test@example.com -zone example.com -name extra
#
# cronjob entry to run every 5 minutes:
# */5 * * * * /path/to/cloudflare_dyn_dns.sh -key 404613183ab3971a2118ae5bf03d63e032f9e -email test@example.com -zone example.com -name extra >> /path/to/cloudflare_dyn_dns.log
# 
# will both set the type A DNS record for extra.example.com to the current public IP address for user test@example.com with the provided API key

key=
email=
zone=
zone_id=
type=A
rec_id=
name=
content=
ttl=1
proxied=false

while [ "$1" != "" ]; do
    case $1 in
        -key )     shift
                   key=$1
                   ;;
        -email )   shift
                   email=$1
                   ;;
        -zone )    shift
                   zone=$1
                   ;;
        -zone_id ) shift
                   zone_id=$1
                   ;;
        -type )    shift
                   type=$1
                   ;;
        -rec_id )  shift
                   rec_id=$1
                   ;;
        -name )    shift
                   name=$1
                   ;;
        -content ) shift
                   content=$1
                   ;;
        -ttl )     shift
                   ttl=$1
                   ;;
        -proxied ) shift
                   proxied=$1
                   ;;
        * )        echo "unknown parameter $1"
                   exit 1
    esac
    shift
done

if [ "$content" = "" ]
then
    content=`curl -s http://myexternalip.com/raw`
    if [ "$content" = "" ]
    then
        date
        echo "No IP address to set record value with."
        exit 1
    fi
fi

if [ "$name" = "" ]
then
    echo "You must provide the name of the record you wish to change."
    exit 1
fi

if [ "$zone" = "" ]
then
    echo "You must provide the domain you wish to change."
    exit 1
fi

existing_content=`host -t $type $name.$zone | sed -E 's/.+?\s+([^\s]+)$/\1/'`

if [ "$content" = "$existing_content" ]
then
    echo "Existing record value $existing_content is the same as provided content $content. Exiting."
    exit
fi

if [ "$key" = "" ]
then
    echo "You must provide your user API token."
    exit 1
fi

if [ "$email" = "" ]
then
    echo "You must provide your user email."
    exit 1
fi

# Get the zone id for the entry we're trying to change if it's not provided
if [ "$zone_id" = "" ]
then
    zone_response_json=`curl -X GET "https://api.cloudflare.com/client/v4/zones?name=$zone" -H "X-Auth-Email: $email" -H "X-Auth-Key: $key" -H "Content-Type: application/json"`
    zone_id=`echo $zone_response_json | sed -E "s/.+\"result\":\[\{\"id\":\"([a-f0-9]+)\"[^\}]+$zone.+/\1/g"`
    if [ "$zone_id" = "" ]
    then
        echo "Cloudflare DNS Zone id could not be found, please make sure it exists"
        exit 1
    fi
fi

# Get the record id for the entry we're trying to change if it's not provided
if [ "$rec_id" = "" ]
then
    rec_response_json=`curl -X GET "https://api.cloudflare.com/client/v4/zones/$zone_id/dns_records?name=$name.$zone" -H "X-Auth-Email: $email" -H "X-Auth-Key: $key" -H "Content-Type: application/json"`
    rec_id=`echo $rec_response_json | sed -E "s/.+\"result\":\[\{\"id\":\"([a-f0-9]+)\"[^\}]+\"type\":\"$type\"[^\}]+$name.$zone.+/\1/g"`
    if [ "$rec_id" = "" ]
    then
        echo "Cloudflare DNS Record id could not be found, please make sure it exists"
        exit 1
    fi
fi

# Update the DNS record
update_response=`curl -X PUT "https://api.cloudflare.com/client/v4/zones/$zone_id/dns_records/$rec_id" -H "X-Auth-Email: $email" -H "X-Auth-Key: $key" -H "Content-Type: application/json" --data "{\"id\":\"$rec_id\",\"type\":\"$type\",\"name\":\"$name.$zone\",\"content\":\"$content\",\"ttl\":\"$ttl\",\"proxied\":$proxied}"`

success_val=`echo $update_response | sed -E "s/.+\"success\":(true|false).+/\1/g"`
if [ "$success_val" = "true" ]
then
    echo "Record Updated."
else
    echo "Record update failed."
    exit 1
fi

Firewalld, firewall-cmd and Fail2Ban

Basically I’ve been looking at upgrading a web-server to the latest version of Fedora 19, or when it’s released later this year CentOS 7.0 (providing it’s easy for them when RHEL 7.0 is released), however knowing that iptables is now becoming redundant in favour of firewalld in Fedora I started looking at updating my web-server install script to work with firewalld.  Knowing part of that is Fail2Ban and that uses iptables my first port of call was finding a way of getting these two working together.

My first obvious search for “firewalld fail2ban” returned nothing helpful whatsoever, just people wanting a conf file to get it working with no actually helpful response, however once I found that firewalld uses firewall-cmd on the command line to control the rules I searched for that. This turned up a current bug posted on RedHat’s BugZilla: https://bugzilla.redhat.com/show_bug.cgi?id=979622 , where it turns out a very helpful soul, Edgar Hoch, has created an action.d conf file to get it all working: https://bugzilla.redhat.com/attachment.cgi?id=791126

Fedora 19, GNOME 3 and nVidia graphics

After upgrading to the latest version of Fedora a few months ago I was terribly un-impressed. The box in question had been upgraded every 6 months (-ish, thanks to Fedora 18) since Fedora 14 and I’d never had any issues, but then came Fedora 19.

To be fair it wasn’t Fedora’s fault per say, it was GNOME 3 and the open source nVidia graphics drivers. The desktop looked ok when you booted the box, but if you tried to use the Activities section, none of the transparency worked, and a lot of the Favourite icons in the dock had a luminous green behind them when you hovered over them.  What was worse was trying to launch a non-favourite application, click to do that and you could see the first 6 frequently used ones, but no others, and none under the “all” tab. This obviously made the whole experience pretty much unusable.

I went through the obvious investigations, straight away looking for some better nVidia graphics drivers.  I didn’t expect to find any official nvidia drivers after Linus’ hilarious rant last year. However, it turned out there was. I first tried downloading them from nVidia but their installers were less than helpful, and none wanted to install on my system regardless of fulfilling their dependencies. I then tried looking elsewhere and remembered the trusty basic linux guide site If !1 0. I found a guide on there for Fedora 18, and adapted it for Fedora 19, but unfortunately that wouldn’t work due to a mass amount of package conflicts.  I’d been meaning to wipe the system for a while and start again, so backed up the /etc/ folder to another drive, wiped the partitions, then installed Fedora 19 and used the guide again and all was fine and dandy.  The boot screen is the basic plymouth one rather than the more graphical splash one, but apart from that everything works and I don’t have awful un-usable graphics anymore.

If you want the latest guide, which is for Fedora 19, go here: http://www.if-not-true-then-false.com/2013/fedora-19-nvidia-guide/

BETT 2013

Well, Just over a week ago I got back from attending my first BETT show, and I have to say it was an amazing experience.

It had everything, from hearing about 3 seconds and having a fleeting glance of Brian Cox, providing my “technical advice” to customers when I could, spending hours packing / handing out bags, many trips to storage to retrieve stock, meeting hundreds of enthusiastic customers eager to get our bags or stress balls, and clearly the best bit on the stand being when we had quite a few of the staff doing “Double Dream Hands” on Saturday (I mean, why wouldn’t we!!!).

Overall it had quite a familiar experience to when I previously worked as both a waiter and barman during my 6th form college & university years.  The at times very fast paced work, but also constant interaction with the general public is always something I’ve enjoyed and fed off (yep, call me a wierdo, but I enjoy running about at work every once in a while, and this was definitely one of those times). The atmosphere amongst the staff was also brilliant. Everyone pulled together and created a great atmosphere. This kept everyone going and kept everything working like a well oiled machine to try to give the customer everything they wanted, even when (most of the time) all of demonstration pods were busy, and our sales team couldn’t give any more demonstrations due to the constant influx of enthused new and existing customers.

As purely a developer it was also a great experience. Seeing how enthusiastic customers are to get their hands on our new product, and hearing how much they feel it’ll help in so many ways in their school, makes you enthused both as an individual, and as part of the team, to carry on producing the already great product we create to make a massive difference to the education of children.

Overall as I’ve already done on twitter I’d definitely like to thank both all the visitors to our stand, and all my colleagues, both those I finally properly met at the event, and those I’d already been working with, you all helped contribute to a thoroughly enjoyable working week.

NginX – Blocking per IP address or range

Yep I know what your thinking, blocking  by IP inside NginX, shouldn’t you be doing that at firewall level instead? Yes, if it comes from the actual IP, you should. Programs such as Fail2ban provide the functionality to automatically block unscrupulous IPs via iptables thus the traffic never gets anywhere near your software.

The problem comes however when your using a service such as Cloudflare. As far as the firewall is concerned the IP is that of Cloudflare, not the actual end user. Thus we then have to fall back on the next layer, which in this case is NginX. Utilising the RealIP Module we can set the user’s actual IP address into the correct server variable. Once we’ve done this anything running from NginX (PHP-FPM etc.) will see the remote address as the correct one rather than Cloudflare’s IP.

Anyway, to the point, blocking the IPs you don’t like. To do this you simply need to use NginX’s geo module. With this you can compare the provided remote address to a list and set a variable inside the http definition in nginx.conf:

geo $ban_ip {
default 0;
10.1.0.0/24 1;
192.168.0.254 1;
};

Once you’ve set this up you can use that variable inside the individual server definitions to send different http response codes for those specific IP addresses:

if ($ban_ip) {
return 404;
}

or you can tell NginX to simply drop the connection,

if ($ban_ip) {
return 444;
}

which if combined with Cloudflare will show the user Cloudflare’s cached version of your site, so the end user is still getting your site, without your server ever serving their client anything.

Thanks for this lovely snippet of information go to Alexander Azarov.

Fedora 18 – non-graphical boot and ifconfig

After downloading Fedora 18 and creating a minimal install virtual machine I went straight to doing the default I always do.  As I was creating a test server I need to be able to see what’s happening during boot so I disable the graphical boot.

Previously (at-least up to Fedora 15) I’d used the plymouth commands to switch the graphical boot to details which had worked.

[[email protected] ~]# plymouth-set-default-plugin details
[[email protected] ~]# /usr/libexec/plymouth/plymouth-update-initrd

However, when I tried this with Fedora 18, nope, not working, the community to the rescue. Another individual  (Nigel Smith) had had the same issue and found the solution in editing the default grub configuration file. So if you need the same visit here:

http://nwsmith.blogspot.co.uk/2012/10/customizing-grub2-boot-options-in.html

While I was at it I also noticed that ifconfig produced a “Command not found”. Erm … wha? Where did that go? Isn’t that like a basic linux command? Turns out in Fedora 18 it’s been removed due to the alternative and replacement iproute package being in place for “many years”. So you’ve now got 2 choices:

1. use the ip command:

ip addr

2. install the net-tools package:

yum -y install net-tools

Formatting a Date in PHP using ISO Format

We all know how to format a date in PHP when using the date functions, but what happens if you’ve only got the ISO format? This doesn’t work with PHP’s date functions.

Well I got this exact situation whilst using Zend_Locale in Zend Framework. Because the locale data files utilised are sourced externally the format comes back in ISO format.  A conversion function is provided (Zend_Locale_Format::convertPhpToIsoFormat) however that’s converting the wrong way and won’t help in this situation.

I went ahead and wrote a quick function which will return a formatted date using a provided ISO format, rather than PHP format.  It works like the PHP function and accepts the same parameters.

You can find the function as a gist on github:

<?php

function date_iso($format, $timestamp = null)
{
	if ($timestamp === null) {
		$timestamp = time();
	}

	$convert = array(
		'a' => 'A' , 'B' => 'B', 'D' => 'z', 'ddd' => 't', 'dd' => 'd', 'd' => 'j',
		'EEEE' => 'l', 'EE' => 'D', 'eee' => 'N', 'e' => 'w', 'HH' => 'H', 'H' => 'G',
		'hh' => 'h', 'h' => 'g', 'I' => 'I', 'l' => 'L', 'MMMM' => 'F', 'MMM' => 'M',
		'MM' => 'm', 'M' => 'n', 'mm' => 'i', 'r' => 'r', 'SS' => 'S', 'ss' => 's',
		'U' => 'U', 'ww' => 'W', 'X' => 'Z', 'YYYY' => 'o', 'yyyy' => 'Y', 'yy' => 'y',
		'ZZZZ' => 'P', 'zzzz' => 'e', 'Z' => 'O', 'z' => 'T'
	);

	$values = preg_split(
		'/(a|B|D|d{1,3}|EEEE|EE|eee|e|HH|H|hh|h|I|l|M{1,4}|mm|r|SS|ss|U|ww|X|YYYY|yyyy|yy|ZZZZ|zzzz|Z|z|[^a-zA-Z]+)/',
		$format,
		-1,
		PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
	);
	foreach ($values as $key => $value) {
		if (isset($convert[$value])) {
			$values[$key] = date($convert[$value], $timestamp);
		}
	}
	return implode($values);
}

Installing MongoDB on a Linux distro using SystemD instead of inittab

While trying to get MongoDB working on a Fedora 15 test server I found that there was no way of installing the latest version with SystemD control due to a pre-existing known bug.

To Mongo’s credit there is a file provided in the source under rpm/init.d-mongod, however when it comes to this being used by SystemD, well it just errors.

This was frustrating, but as I was doing it on a VM, I did what any logical person would do. Installed Mongo from the package manager, took a copy of the required SystemD files, reverted to a snapshot, then installed the latest version of Mongo from source.

After this I adapted the mongod.service file to use the correct locations, ensured all the required directories, files and users were present on the system then started the service et voila, working latest version of MongoDB on Fedora 15 with SystemD

the two required files are:
/lib/systemd/system/mongod.service

[Unit]
Description=High-performance, schema-free document-oriented database
After=syslog.target network.target
 
[Service]
Type=forking
User=mongod
Group=mongod
PIDFile=/var/run/mongodb/mongod.pid
EnvironmentFile=/etc/sysconfig/mongod
ExecStart=/usr/local/bin/mongod $OPTIONS run
 
[Install]
WantedBy=multi-user.target

/etc/sysconfig/mongod

Or you can just use the RedHat distro based install script I created:

#!/bin/sh

# MongoDB Version
MONGODB_VER='2.2.2'

# Get all the dependencies up to date
yum -y update
yum -y install scons gcc-c++ glibc-devel

# Get the source
cd /usr/local/src/
wget http://downloads.mongodb.org/src/mongodb-src-r$MONGODB_VER.tar.gz
tar xfz mongodb-src-r$MONGODB_VER.tar.gz
cd mongodb-src-r$MONGODB_VER

# Compile and Install
scons all
scons install

# Create the SystemD dependant files
echo '[Unit]
Description=High-performance, schema-free document-oriented database
After=syslog.target network.target
 
[Service]
Type=forking
User=mongod
Group=mongod
PIDFile=/var/run/mongodb/mongod.pid
EnvironmentFile=/etc/sysconfig/mongod
ExecStart=/usr/local/bin/mongod $OPTIONS run
 
[Install]
WantedBy=multi-user.target' > /lib/systemd/system/mongod.service

echo 'OPTIONS="--quiet -f /etc/mongod.conf"' > /etc/sysconfig/mongod

# Setup the required user and group
useradd -r -U mongod

# Setup the required directories
mkdir -p /var/run/mongodb/
mkdir -p /var/log/mongo/
mkdir -p /var/lib/mongo/
chown mongod:mongod /var/run/mongodb/
chown mongod:mongod /var/log/mongo/
chown mongod:mongod /var/lib/mongo/
chmod 0755 /var/log/mongo/
chmod 0755 /var/run/mongodb/
chmod 0755 /var/lib/mongo

# Start the new service and enable it on boot
systemctl --system daemon-reload
systemctl start mongod.service
systemctl enable mongod.service

Giving you lovely snippets of helpful, strange or otherwise random information