<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>iamtgc</title>
	
	<link>http://iamtgc.com</link>
	<description />
	<lastBuildDate>Thu, 01 Mar 2012 19:46:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Iamtgc" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="iamtgc" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Implementing a Lightbox in WordPresss</title>
		<link>http://iamtgc.com/2012/03/01/implementing-a-lightbox-in-wordpresss/</link>
		<comments>http://iamtgc.com/2012/03/01/implementing-a-lightbox-in-wordpresss/#comments</comments>
		<pubDate>Thu, 01 Mar 2012 16:29:46 +0000</pubDate>
		<dc:creator>tgc</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Wordpress]]></category>

		<guid isPermaLink="false">http://iamtgc.com/?p=731</guid>
		<description><![CDATA[The problem that I have encountered while researching various options for implementing a JavaScript lightbox in WordPress, is that they generally require you to add either a class, id, or rel attribute to your image link. This may not be &#8230; <a href="http://iamtgc.com/2012/03/01/implementing-a-lightbox-in-wordpresss/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The problem that I have encountered while researching various options for implementing a JavaScript lightbox in WordPress, is that they generally require you to add either a class, id, or rel attribute to your image link. This may not be an issue for newly authored content, but for those of us with a large volume of existing content, it can be a nightmare.</p>
<p>One solution proposed on <a title="Fancybox - Fancy jQuery lightbox alternative| Tips &amp; Tricks" href="http://fancybox.net/blog" target="_blank">Fancybox&#8217;s Tips &amp; Tricks</a> page, is to apply the lightbox only to those &lt;a&gt; tags whose href attribute ends with .jpg, .png or .gif:</p>
<pre class="brush:js;">$("a[href$=.jpg],a[href$=.png],a[href$=.gif]").fancybox();</pre>
<p>This may work for many situations, but it could have unintended consequences depending on your content, so I chose a different approach.<br />
<span id="more-731"></span><br />
The lightbox I ended up going with is <a title="ColorBox, A jQuery Lightbox" href="http://jacklmoore.com/colorbox/" target="_blank">Colorbox</a>, but <a title="30 Efficient jQuery Lightbox Plugins" href="http://www.designyourway.net/blog/resources/30-efficient-jquery-lightbox-plugins/" target="_blank">many others</a> exist, and this article should apply to a majority of them with minimal modification.</p>
<p>If you&#8217;ve read any of my <a title="Add Google +1 to your WordPress blog" href="http://iamtgc.com/2011/07/13/add-google-plus-one-to-your-wordpress-blog/">other</a> <a title="Integrating a Google Custom Search Engine into your WordPress blog" href="http://iamtgc.com/2011/07/10/integrating-a-google-custom-search-engine-into-your-wordpress-blog/">articles</a> you know I usually prefer to avoid using plugins, especially for these simple tasks.</p>
<p>Once you&#8217;ve <a href="http://jacklmoore.com/colorbox/colorbox.zip" title="ColorBox, A jQuery Lightbox">downloaded</a> the lightbox of your choice, choose a location to place the javascript and accompanying stylesheet, in this example I&#8217;ve placed both in <strong>/js</strong>. Then place the following in <strong>functions.php</strong>. This example uses a <a href="http://codex.wordpress.org/Child_Themes" title="Child Themes &laquo; WordPress Codex" target="_blank">child theme</a>, if you&#8217;re not, you should replace <a href="http://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri" title="Function Reference/get stylesheet directory uri &laquo; WordPress Codex" target="_blank">get_stylesheet_directory_uri()</a> with <a href="http://codex.wordpress.org/Function_Reference/get_template_directory_uri" title="Function Reference/get template directory uri &laquo; WordPress Codex" target="_blank">get_template_directory_uri()</a>.</p>
<pre class="brush:php;">function tgc_scripts_method() {
    wp_register_script( 'jquery.colorbox',
                        get_stylesheet_directory_uri() . '/js/jquery.colorbox-min.js',
                        array( 'jquery' ) );
    wp_enqueue_script( 'jquery.colorbox' );
}

add_action( 'wp_enqueue_scripts', 'tgc_scripts_method' );
</pre>
<p>Next you&#8217;ll need to add the relevant css and javascript to <strong>header.php</strong>, as in functions.php above, this assumes a child theme. If you&#8217;re using a parent theme, replace the <em>stylesheet_directory</em> parameter with <em>template_directory</em> in the <a href="http://codex.wordpress.org/Function_Reference/bloginfo" title="Function Reference/bloginfo &laquo; WordPress Codex" target="_blank">bloginfo</a> function.</p>
<pre class="brush:html;">
&lt;link rel="stylesheet" type="text/css" media="all" href="&lt;?php bloginfo( 'stylesheet_directory' ); ?&gt;/js/colorbox.css" /&gt;
&lt;script&gt;
    jQuery(document).ready(function () {
        jQuery('a[rel="colorbox"]').colorbox({ rel:"nofollow" });
    });
&lt;/script&gt;
</pre>
<p>Last, we need to modify our &lt;a&gt; tags to include a <em>rel</em> attribute with the value of <em>colorbox</em>. We do this by adding a <a href="http://codex.wordpress.org/Function_Reference/add_filter" title="Function Reference/add filter &laquo; WordPress Codex" target="_blank">filter</a> to <a href="http://codex.wordpress.org/Function_Reference/the_content" title="Function Reference/the content &laquo; WordPress Codex" target="_blank">the_content</a>. This avoids having to update each post or modify the database. Additionally, if we change our mind on which lightbox we want to use, or how we&#8217;re invoking it, the modifications will be a lot simpler.</p>
<p>The regular expression we will use targets &lt;a&gt; tags which link to an image (.jpg, .png, or .gif) and where the link text is an &lt;img&gt; tag of the same image. For example:</p>
<pre class="brush:html;">
&lt;a href="image.jpg"&gt;&lt;img src="image-1024x701.jpg"/&gt;&lt;/a&gt;
</pre>
<p>Here is what you&#8217;ll need to add to <strong>functions.php</strong></p>
<pre class="brush:php;">
function tgc_colorbox_content_filter( $content ) {
        $url_regex = '/(&lt;a .*href="(.*)\.(jpg|png|gif)")(.*&gt;&lt;img .*src="\2.*\.\3".*&gt;&lt;\/a&gt;)/i';
        $url_replace = '$1 rel="colorbox" $4';

        return preg_replace( $url_regex, $url_replace, $content );
}

add_filter( 'the_content', 'tgc_colorbox_content_filter' );
</pre>
]]></content:encoded>
			<wfw:commentRss>http://iamtgc.com/2012/03/01/implementing-a-lightbox-in-wordpresss/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Move the Navigation Bar in a Twentyeleven Child Theme</title>
		<link>http://iamtgc.com/2012/02/16/move-the-navigation-bar-in-a-twentyeleven-child-theme/</link>
		<comments>http://iamtgc.com/2012/02/16/move-the-navigation-bar-in-a-twentyeleven-child-theme/#comments</comments>
		<pubDate>Fri, 17 Feb 2012 02:58:33 +0000</pubDate>
		<dc:creator>tgc</dc:creator>
				<category><![CDATA[Wordpress]]></category>

		<guid isPermaLink="false">http://iamtgc.com/?p=705</guid>
		<description><![CDATA[If you don&#8217;t like the default location of twentyeleven&#8217;s navigation bar, there&#8217;s good news, the theme is coded in such a way where it&#8217;s very simple to move with just a few lines of CSS. As I&#8217;ve mentioned in previous &#8230; <a href="http://iamtgc.com/2012/02/16/move-the-navigation-bar-in-a-twentyeleven-child-theme/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you don&#8217;t like the default location of <a href="http://wordpress.org/extend/themes/twentyeleven" title="Twenty Eleven Theme">twentyeleven&#8217;s</a> navigation bar, there&#8217;s good news, the theme is coded in such a way where it&#8217;s very simple to move with just a few lines of CSS.</p>
<p>As I&#8217;ve mentioned in <a href="http://iamtgc.com/2011/07/15/adding-the-sidebar-to-a-twentyeleven-child-theme/" title="Adding the sidebar to a Twentyeleven child theme" target="_blank">previous</a> <a href="http://iamtgc.com/2011/08/12/remove-default-header-images-from-twentyeleven-child-theme/" title="Remove the default header images from a Twentyeleven child theme" target="_blank">articles</a>, you&#8217;re strongly encouraged to tackle this using <a href="http://codex.wordpress.org/Child_Themes" title="Child Themes" target="_blank">child themes</a>.</p>
<p>First we begin by inspecting the current theme with <a href="http://getfirebug.com/" title="Firebug">Firebug</a>. Since the navigation bar is the element we&#8217;re interested in, that&#8217;s the one we&#8217;ll inspect with Firebug. We&#8217;re interested in the layout as seen in the image below.<br />
<span id="more-705"></span><br />
<a href="http://iamtgc.com/wp-content/uploads/2012/02/twentyeleven-firebug.jpg" rel="colorbox" ><img src="http://iamtgc.com/wp-content/uploads/2012/02/twentyeleven-firebug-1024x701.jpg" alt="" title="twentyeleven-firebug" width="640" height="438" class="aligncenter size-large wp-image-717" /></a></p>
<p>As it turns out, the height of the navigation bar is 43px, that gives us all the information we really need to know to move the navigation bar.</p>
<p>Here&#8217;s what our child theme&#8217;s <strong>style.css</strong> looks like.</p>
<pre class="brush:css;">
/*
Theme Name: iamtgc Theme Development
Description: Child theme for the Twenty Eleven theme
Author: tgc
Template: twentyeleven
*/

@import url("../twentyeleven/style.css");

#branding { padding-top: 43px; }

#branding #searchform { padding-top: 43px; }

#access { position: absolute; top: 0; }
</pre>
<p>And here&#8217;s what our new theme looks like once it&#8217;s activated. </p>
<p><a href="http://iamtgc.com/wp-content/uploads/2012/02/twentyeleven-navbar-top.jpg" rel="colorbox" ><img src="http://iamtgc.com/wp-content/uploads/2012/02/twentyeleven-navbar-top-1024x520.jpg" alt="" title="twentyeleven-navbar-top" width="640" height="325" class="aligncenter size-large wp-image-707" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://iamtgc.com/2012/02/16/move-the-navigation-bar-in-a-twentyeleven-child-theme/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Add Pinterest’s “Pin It” Button To Your WordPress Blog</title>
		<link>http://iamtgc.com/2012/02/01/add-pinterests-pin-it-button-to-your-wordpress-blog/</link>
		<comments>http://iamtgc.com/2012/02/01/add-pinterests-pin-it-button-to-your-wordpress-blog/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 00:15:10 +0000</pubDate>
		<dc:creator>tgc</dc:creator>
				<category><![CDATA[Wordpress]]></category>

		<guid isPermaLink="false">http://iamtgc.com/?p=666</guid>
		<description><![CDATA[Even if you haven&#8217;t been fortunate enough to receive a Pinterest invite yet, chances are you&#8217;ve seen their &#8220;Pin It&#8221; button somewhere in your daily browsing. Fortunately you don&#8217;t need an invitation to add the &#8220;Pin It&#8221; button to your &#8230; <a href="http://iamtgc.com/2012/02/01/add-pinterests-pin-it-button-to-your-wordpress-blog/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Even if you haven&#8217;t been fortunate enough to receive a <a href="http://pinterest.com" title="Pinterest">Pinterest</a> invite yet, chances are you&#8217;ve seen their &#8220;Pin It&#8221; button somewhere in your daily browsing.  Fortunately you don&#8217;t need an invitation to add the &#8220;Pin It&#8221; button to your website.  In this article I will show you how to add the &#8220;Pin It&#8221; button to your WordPress blog.<br />
<span id="more-666"></span><br />
To get an understanding of the API, you can visit Pinterest&#8217;s <a href="http://pinterest.com/about/goodies/" title="Pinterest / Goodies" target="_blank">Goodies</a> page, and scroll down to the section labeled <strong>&#8220;Pin It&#8221; Button For Websites</strong>.  There you&#8217;ll see the following code generator.</p>
<p><a href="http://iamtgc.com/wp-content/uploads/2012/01/pinterest-form.jpg" rel="colorbox" ><img src="http://iamtgc.com/wp-content/uploads/2012/01/pinterest-form.jpg" alt="" title="Pinterest Form" width="630" height="456" class="aligncenter size-full wp-image-677" /></a></p>
<p>Once you begin populating the fields, your changes are reflected in the code window.  As you may notice, the URLs you&#8217;re Pinning will need to be <a href="http://en.wikipedia.org/wiki/Percent-encoding" title="Percent-encoding - Wikipedia, the free encyclopedia" target="_blank">URL encoded</a>.</p>
<p><a href="http://iamtgc.com/wp-content/uploads/2012/01/pinterest-form-partial1.jpg" rel="colorbox" ><img src="http://iamtgc.com/wp-content/uploads/2012/01/pinterest-form-partial1.jpg" alt="" title="Partially Populated Pinterest Form" width="625" height="449" class="aligncenter size-full wp-image-686" /></a></p>
<p>In order to implement this code generation in WordPress, we&#8217;ll get the <strong>URL of the webpage the pin is on</strong> using</p>
<pre class="brush:php;">
&lt;?php echo urlencode( get_permalink() ); ?&gt;
</pre>
<p>The <strong>URL of the image to be pinned</strong> using the post&#8217;s full sized featured image.</p>
<pre class="brush:php;">
&lt;?php echo urlencode( wp_get_attachment_url( get_post_thumbnail_id() ) ); ?&gt;
</pre>
<p>And for the <em>optional</em> <strong>Description of the Pin</strong>, we&#8217;ll use the post&#8217;s title</p>
<pre class="brush:php;">
&lt;?php echo urlencode( get_the_title() ); ?&gt;
</pre>
<p>When we put it all together, here&#8217;s what the relevant excerpt of our <strong>loop-single.php</strong> will look like. If you want to include the Pin Count along with the &#8220;Pin It&#8221; button, you can change the <strong>count-layout</strong> attribute to either <strong>horizontal</strong> or <strong>vertical</strong>.</p>
<pre class="brush:html;">
&lt;div id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class(); ?&gt;&gt;
&lt;h1 class="entry-title"&gt;&lt;?php the_title(); ?&gt;
     &lt;a href="http://pinterest.com/pin/create/button/?url=&lt;?php echo urlencode(get_permalink()); ?&gt;&#038;media=&lt;?php echo urlencode(wp_get_attachment_url(get_post_thumbnail_id())); ?&gt;&#038;description=&lt;?php echo urlencode( get_the_title()); ?&gt;" class="pin-it-button" count-layout="none"&gt;Pin It&lt;/a&gt;
     &lt;script type="text/javascript" src="http://assets.pinterest.com/js/pinit.js"&gt;&lt;/script&gt;
&lt;/h1&gt;

&lt;div class="entry-meta"&gt;
&lt;?php twentyten_posted_on(); ?&gt;
&lt;/div&gt;&lt;!-- .entry-meta --&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://iamtgc.com/2012/02/01/add-pinterests-pin-it-button-to-your-wordpress-blog/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PostgreSQL Database Encryption</title>
		<link>http://iamtgc.com/2011/09/13/postgresql-database-encryption/</link>
		<comments>http://iamtgc.com/2011/09/13/postgresql-database-encryption/#comments</comments>
		<pubDate>Tue, 13 Sep 2011 14:01:49 +0000</pubDate>
		<dc:creator>tgc</dc:creator>
				<category><![CDATA[Postgres]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://iamtgc.com/?p=194</guid>
		<description><![CDATA[For last decade data breaches and data losses of Social Security numbers, credit card numbers, or one of a slew of other pieces of private information, have landed businesses on the front page of major newspapers, and in some instances &#8230; <a href="http://iamtgc.com/2011/09/13/postgresql-database-encryption/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>For last decade data breaches and data losses of Social Security numbers, credit card numbers, or one of a slew of other pieces of private information, have landed businesses on the front page of major newspapers, and in some instances with legal liability.</p>
<p>I knew when I had an opportunity to work an application which handled sensitive information, that it had to be done with the protection of this information as the number one priority.<br />
<span id="more-194"></span><br />
I began familiarizing myself with the application by starting with the PostgreSQL database back-end.  The <a href="http://www.postgresql.org/docs/8.4/static/pgcrypto.html">pgcrypto</a> module was present, but none of it&#8217;s functions were currently in use.</p>
<p>For the remainder of the article, we will take a look at how to use some of the pgcrypto <a href="http://www.postgresql.org/docs/8.4/static/pgcrypto.html#AEN116836" title="F.23.3. PGP encryption functions" target="_blank">PGP encryption functions</a> to encrypt sensitive data.  </p>
<p>First we will need to create our table.  For the purposes of our example, the table will contain only one column.</p>
<pre class="brush:sql;">
CREATE TABLE messages (
   message bytea
);
</pre>
<p>Next we need to create our PGP keys.  This process is outlined in the PostgreSQL pgcrypto documentation <a href="http://www.postgresql.org/docs/8.4/static/pgcrypto.html#AEN116992" title="F.23.3.8. Generating PGP keys with GnuPG" target="_blank">here</a>.</p>
<p>Once we&#8217;ve created our PGP keys we can test the encryption functionality using the below Python code.  Here we are using the public key to encrypt the word &#8220;testing&#8221; and inserting the result into our table.</p>
<pre class="brush:python;">
#!/usr/bin/env python

import psycopg2

conn = psycopg2.connect("dbname='crypto_test' user='tgc' host='localhost'")

curs = conn.cursor()

f = open("public.key", "r")
key = f.read()

curs.execute("INSERT INTO messages (message) VALUES (pgp_pub_encrypt('testing', dearmor('%s')))" % (key))

conn.commit()
</pre>
<p>Did it work?  Let&#8217;s see what was actually inserted into our table.</p>
<pre class="brush:plain;">
crypto_test=# select * from messages;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             message
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 \301\301N\003~_\240V\321\032$\006\020\010\000\271H9\327\224\0336\245:\242\202\352B\232\314\261\2263\032#Z\343\344\365;m\333\337\3226`\352\344\017H\304\373|\213\022\246\343$\351Z\307\366`&lt;\266\206&lt;\330\332\024\203xX\270S\261\317\\\317\336bz\241\307\337\333`\203\020\311J?Y\013\331\021b{\220[S\011\032eu\374s\265l\336JiD\217\364P\275\272\004i\220\214\205\3111\206&lt;\361\025%\235+U\253\202\340\250V\247\361\310\334f\307\322x=&gt;\315x\263;\307w\335\351~--\363\350\361]5)\203\327"\254vk4o\211\244s^r\301\310\374=\312L\347\233\263\232\256~\337\033tM&gt;\012\001C\200\345\303r\326\354{\005\3149\314\211\246\210\273\002~Z\317\270p\237\376\307\025\377r\370\221G\324\306\303\355'\301\020\357/\2049\342\222}\327K\321\347\322+\343Y\220C\027vn\027\356V-\203\355\311\033\355A)\277\266\224\256\022\007\377_\031:\015\345-\264Rj~n\207\240/\370D\3143z\305k\245/f'\004\230r[\207\321H\240a^\247\015\037\351\276!~\354\031\314~)\224\364r\354\036\337\376\006\024K\300ih\335\377\011\256C\262\253\016\210ZN\272\231{\332\304\303\332\003;\221\022\004\275\335\330$\027v\355\004,f\2713\266\352\311\027\326\316\3742LMM\353\037\222C\264\240\275&gt;,\210o\326\212F_@G\306\276\274\332\247\256\336\027U\377\224\313\221&gt;b\355\003K\300\231c&lt;H\236;[\027!\263\311\260V\230\200Jp\333\023\027\004Y\273\321\306N\024%\376\010\317\351\016\332&#038;\030\213\225\017#\006\243nb\332r\363~\013\336\207\337\005\024\322\351$KG\334\376\260\366\025]K\031\037w\016O\2358\277\032?s%\300R\263\031R\273S:\376&#038;\377\326\365\240_\252+;\002+\243\034\257\364\377\322U\320F\005\260\230OS\373~\3228\001*\304\265\204\273\335\236\022\305\312\233\350\011\231\211\250\2103\273\305\214\1770g\305k\254\245!X\262\216\000\020K%~OsJ\365m"\330*\246KX"K4\350\013\214#
(1 row)
</pre>
<p>Well, that&#8217;s certainly a far cry from &#8220;testing&#8221;.</p>
<p>Now for the code that decrypts our message.</p>
<pre class="brush:python;">
#!/usr/bin/env python

import psycopg2

conn = psycopg2.connect("dbname='crypto_test' user='tgc' host='localhost'")

curs = conn.cursor()

f = open("secret.key", "r")
key = f.read()

curs.execute("SELECT pgp_pub_decrypt(message, dearmor('%s')) from messages" % (key))

rows = curs.fetchall()

for row in rows:
    print row[0]
</pre>
<p>Let&#8217;s try running our decryption script</p>
<pre class="brush:shell;">
$ python ./test-decrypt.py
testing
</pre>
<p><strong>Note:</strong> depending on the type of data you are encrypting, the functions <strong>pgp_pub_encrypt_bytea</strong> and <strong>pgp_pub_decrypt_bytea</strong> are also available.</p>
]]></content:encoded>
			<wfw:commentRss>http://iamtgc.com/2011/09/13/postgresql-database-encryption/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exploring Triggers in MySQL and PostgreSQL</title>
		<link>http://iamtgc.com/2011/08/15/exploring-triggers-in-mysql-and-postgresql/</link>
		<comments>http://iamtgc.com/2011/08/15/exploring-triggers-in-mysql-and-postgresql/#comments</comments>
		<pubDate>Mon, 15 Aug 2011 13:25:37 +0000</pubDate>
		<dc:creator>tgc</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Postgres]]></category>

		<guid isPermaLink="false">http://iamtgc.com/?p=533</guid>
		<description><![CDATA[Recently I was working on a car maintenance database. The database stores, among other things, odometer reading, miles per fill up, number of gallons per fill up, and cost per gallon. One of the missing pieces of information I wanted &#8230; <a href="http://iamtgc.com/2011/08/15/exploring-triggers-in-mysql-and-postgresql/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Recently I was working on a car maintenance database.  The database stores, among other things, odometer reading, miles per fill up, number of gallons per fill up, and cost per gallon.  One of the missing pieces of information I wanted to report on is the miles per gallon I was achieving.  While this is trivial to insert, I didn&#8217;t want to modify the client which was already deployed and running.  Since the data to determine this value was already present, I turned to database triggers to help me record this value.</p>
<p>Wikipedia describes <em>&#8220;A <a href="http://en.wikipedia.org/wiki/Database_trigger" title="Database trigger - Wikipedia" target="_blank">database trigger</a> is procedural code that is automatically executed in response to certain events on a particular table or view in a database.&#8221;</em></p>
<p>In our case, the procedural code we want to execute is the computation of our miles per gallon, and the event we are responding to is an insert into our table.  In this article I will outline how to create these triggers in both MySQL and PostgreSQL.<br />
<span id="more-533"></span><br />
Our triggers will be applied to the following table.</p>
<pre class="brush:sql;">
CREATE TABLE mileage (
   miles float,
   gallons float,
   mpg float
);
</pre>
<p>The following was tested in MySQL 5.5.14, but should work on other versions as well.</p>
<p>Let&#8217;s create our trigger.  The key things to note here are <strong>BEFORE INSERT</strong>, since we want to insert the mpg value along with the miles and gallons, and <strong>NEW</strong>, since we are referring to a column of a new row to be inserted.</p>
<pre class="brush:sql;">
-- MySQL
CREATE TRIGGER trig__mileage BEFORE INSERT ON mileage FOR EACH ROW SET NEW.mpg  = NEW.miles / NEW.gallons;
</pre>
<p>Now with our trigger created, we can test to see if it fires correctly.  If it fires correctly, we can expect our mpg column to be populated, otherwise it will be NULL.</p>
<pre class="brush:sql;">
-- MySQL
INSERT INTO mileage (miles, gallons) VALUES ( 250, 10 )

SELECT * FROM mileage;
+-------+---------+------+
| miles | gallons | mpg  |
+-------+---------+------+
|   250 |      10 |   25 |
+-------+---------+------+
</pre>
<p>Success!  It really is that simple.  Additional documentation, including more complex examples, can be found <a href="http://dev.mysql.com/doc/refman/5.5/en/create-trigger.html" title="MySQL ::   MySQL 5.5 Reference Manual :: 12.1.15 CREATE TRIGGER Syntax" target="_blank">here</a>.</p>
<p>Now on to PostgreSQL.  These were tested on PostgreSQL 8.3.15, but should work on other versions as well.</p>
<p>The first thing to note is the <a href="http://www.postgresql.org/docs/8.3/static/sql-createtrigger.html" title="PostgreSQL: Documentation: Manuals: PostgreSQL 8.3: CREATE TRIGGER" target="_blank">CREATE TRIGGER</a> statement in PostgreSQL takes a user supplied function as an argument.  This function must return type TRIGGER, and in our instance will be responsible for calculating our miles per gallon.<br />
In our function we use the <strong>NEW</strong> variable, which holds the new database row for insert.</p>
<pre class="brush:sql;">
-- PostgreSQL
CREATE OR REPLACE FUNCTION trig_proc__calculate_mpg() RETURNS TRIGGER AS $_$
BEGIN
   NEW.mpg := NEW.miles / NEW.gallons;
   RETURN NEW;
END $_$
LANGUAGE plpgsql;
</pre>
<p>With our function created, we now create the trigger.</p>
<pre class="brush:sql;">
-- PostgreSQL
CREATE TRIGGER trig__mileage BEFORE INSERT ON mileage FOR EACH ROW EXECUTE PROCEDURE trig_proc__calculate_mpg();
</pre>
<p>And now to test if our trigger fires correctly.</p>
<pre class="brush:sql;">
-- PostgreSQL
INSERT INTO mileage (miles, gallons) VALUES ( 312.3, 12.1 );

SELECT * FROM mileage;
 miles | gallons |       mpg
-------+---------+------------------
 312.3 |    12.1 | 25.8099173553719
</pre>
<p>As you can see, our trigger has populated the mpg column.  Additional documentation on triggers in Postgres can be found <a href="http://www.postgresql.org/docs/8.3/static/triggers.html" title="PostgreSQL: Documentation: Manuals: PostgreSQL 8.3: Triggers" target="_blank">here</a> and <a href="http://www.postgresql.org/docs/8.3/static/plpgsql-trigger.html" title="PostgreSQL: Documentation: Manuals: PostgreSQL 8.3: Trigger Procedures" target="_blank">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://iamtgc.com/2011/08/15/exploring-triggers-in-mysql-and-postgresql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

