<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>GregHeo.com</title>
  <subtitle>Nerdy tech posts</subtitle>
  <id>http://gregheo.com/</id>
  <link href="http://gregheo.com/"/>
  <link href="http://gregheo.com/feed.xml" rel="self"/>
  <updated>2013-03-17T00:00:00Z</updated>
  <author>
    <name>Greg Heo</name>
  </author>
  <entry>
    <title>Custom Keyboards in iOS</title>
    <link rel="alternate" href="/blog/ios-custom-keyboard/"/>
    <id>/blog/ios-custom-keyboard/</id>
    <published>2013-03-17T00:00:00Z</published>
    <updated>2013-03-17T00:00:00Z</updated>
    <author>
      <name>Greg Heo</name>
    </author>
    <content type="html">&lt;p&gt;So you want to make a custom keyboard in your iOS app? Numeric, different key positions, custom button sizing &amp;#8211; the possibilities are endless!&lt;/p&gt;

&lt;p&gt;The tl;dr version: check out &lt;a href='https://github.com/gregheo/clicky'&gt;the sample code on GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h2 id='highlevel_view'&gt;High-level view&lt;/h2&gt;

&lt;p&gt;When a text field becomes the first responder, iOS will show the keyboard view on screen. If it isn&amp;#8217;t already there, it usually slides up from the bottom.&lt;/p&gt;

&lt;p&gt;What you want to do is replace the usual keyboard with your own custom view.&lt;/p&gt;

&lt;h2 id='a_view_is_a_view'&gt;A view is a view&lt;/h2&gt;

&lt;p&gt;Your custom keyboard view is just that, a view. You can construct it using code or from a nib.&lt;/p&gt;

&lt;p&gt;Let&amp;#8217;s say you want to build the ultimate programmer nerd&amp;#8217;s keyboard, something like this:&lt;/p&gt;
&lt;div class='center'&gt;
  &lt;img alt='nerd keyboard' src='/images/blog/ios-keyboard-key.jpg' /&gt;
&lt;/div&gt;
&lt;p&gt;Here&amp;#8217;s what a nib-ified version might look like:&lt;/p&gt;
&lt;div class='center'&gt;
  &lt;img alt='nibby nerd keyboard' src='/images/blog/ios-keyboard-nib.png' /&gt;
&lt;/div&gt;
&lt;h2 id='connecting_the_keyboard_cables'&gt;Connecting the keyboard cables&lt;/h2&gt;

&lt;p&gt;You have your text field, and you have your custom keyboard nib. Connecting them together is easy!&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NerdKeyboard *nerdKeyboard = [[NerdKeyboard alloc] initWithNibName:@&amp;quot;NerdKeyboard&amp;quot;
                                                            bundle:nil];
[self.myTextField setInputView:nerdKeyboard.view];&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Easy! At this point, things will look pretty good. The keyboard appears as expected, but nothing happens when you tap the buttons. Hey, it&amp;#8217;s a &lt;strong&gt;custom&lt;/strong&gt; keyboard, remember? It&amp;#8217;s up to you to handle that part.&lt;/p&gt;

&lt;p&gt;In the sample project, the nib has an accompanying view controller class to handle the button press actions and update the text in the text field. Check out &lt;a href='https://github.com/gregheo/clicky/blob/master/clicky/NerdKeyboard.m'&gt;NerdKeyboard.m&lt;/a&gt; for the details.&lt;/p&gt;

&lt;h2 id='keyboard_clicks'&gt;Keyboard clicks&lt;/h2&gt;

&lt;p&gt;One more small detail: there are no keyboard click sounds! The magic method call you need looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[[UIDevice currentDevice] playInputClick];&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Unfortunately, it&amp;#8217;s not that simple. You can&amp;#8217;t call &lt;code&gt;playInputClick&lt;/code&gt; anywhere you please; iOS limits its use to very specific places.&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s what you need to do:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A view (i.e. your custom keyboard nib) needs to be of a class that implements the &lt;code&gt;UIInputViewAudioFeedback&lt;/code&gt; protocol.&lt;/li&gt;

&lt;li&gt;The class should implement the &lt;code&gt;enableInputClicksWhenVisible&lt;/code&gt; method to return YES.&lt;/li&gt;

&lt;li&gt;The class can then call &lt;code&gt;[[UIDevice currentDevice] playInputClick]&lt;/code&gt; whenever it likes.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Have a look at &lt;em&gt;NerdKeyboard.xib&lt;/em&gt;, &lt;a href='https://github.com/gregheo/clicky/blob/master/clicky/NerdKeyboardView.m'&gt;NerdKeyboardView.m&lt;/a&gt;, and &lt;a href='https://github.com/gregheo/clicky/blob/master/clicky/NerdKeyboardView.h'&gt;NerdKeyboardView.h&lt;/a&gt; for the gory details.&lt;/p&gt;

&lt;p&gt;You can always customize the sound playback too but using &lt;code&gt;playInputClick&lt;/code&gt; means you don&amp;#8217;t have to worry about having an audio file or checking the system volume/mute switch.&lt;/p&gt;

&lt;h2 id='in_closing'&gt;In Closing&lt;/h2&gt;

&lt;p&gt;Of course, &lt;a href='http://xkcd.com/378/'&gt;real programmers&lt;/a&gt; only need zeros&amp;#8230;&lt;/p&gt;</content>
  </entry>
  <entry>
    <title>Restoring In-app Purchases</title>
    <link rel="alternate" href="/blog/iap-restore/"/>
    <id>/blog/iap-restore/</id>
    <published>2012-08-16T00:00:00Z</published>
    <updated>2012-08-16T00:00:00Z</updated>
    <author>
      <name>Greg Heo</name>
    </author>
    <content type="html">&lt;p&gt;I&amp;#8217;ve noticed a bit of chatter on the Internets about this bit in Apple&amp;#8217;s &lt;a href='https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/StoreKitGuide/MakingaPurchase/MakingaPurchase.html#//apple_ref/doc/uid/TP40008267-CH3-SW2'&gt;In-App Purchase Programming Guide&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&amp;#8230;if your application supports product types that must be restorable, you must include an interface that allows users to restore these purchases&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;What the heck? Where am I supposed to find room for a &amp;#8220;Restore&amp;#8221; button in my app, you ask? Luckily, that&amp;#8217;s your problem; what I&amp;#8217;ll talk about here is how to handle the implementation.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h2 id='regular_inapp_purchase'&gt;Regular In-app Purchase&lt;/h2&gt;

&lt;p&gt;Let&amp;#8217;s go over the basics of the simplest purchase before talking about the restore procedure:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SKPayment *payment = [SKPayment paymentWithProductIdentifier:@&amp;quot;productId&amp;quot;];
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
[[SKPaymentQueue defaultQueue] addPayment:payment];&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;StoreKit will take over and if all is well, your transaction observer (&lt;code&gt;self&lt;/code&gt; in this case) will receive a call to this method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (void)paymentQueue:(SKPaymentQueue *)queue
 updatedTransactions:(NSArray *)transactions&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;transactions&lt;/code&gt; array will contain &lt;code&gt;SKPaymentTransaction&lt;/code&gt; objects, each with a &lt;code&gt;transactionState&lt;/code&gt; property. This will usually be &lt;code&gt;SKPaymentTransactionStatePurchased&lt;/code&gt; for a successful purchase.&lt;/p&gt;

&lt;p&gt;Anyhow, you already know all this. Let&amp;#8217;s talk about the dreaded restore.&lt;/p&gt;

&lt;h2 id='the_restoration'&gt;The Restoration&lt;/h2&gt;

&lt;p&gt;The general workflow is pretty similar. Rather than &amp;#8220;purchase&amp;#8221; a specific product, send the &lt;code&gt;restoreCompletedTransactions&lt;/code&gt; message to the queue.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Again, StoreKit will take over and call &lt;code&gt;paymentQueue:updatedTransactions:&lt;/code&gt; for each restored purchase. These will look an awful like regular purchases except the &lt;code&gt;transactionState&lt;/code&gt; will be &lt;code&gt;SKPaymentTransactionStateRestored&lt;/code&gt;. The original transaction details are available in &lt;code&gt;transaction.originalTransaction&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Once all the &lt;code&gt;paymentQueue:updatedTransactions:&lt;/code&gt; calls are made, the transaction observer will receive this callback:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If something goes wrong (StoreKit error, invalid password, user hits &amp;#8220;Cancel&amp;#8221;, etc.) you&amp;#8217;ll receive this callback instead:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (void)paymentQueue:(SKPaymentQueue *)queue
  restoreCompletedTransactionsFailedWithError:(NSError *)error&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id='implementation_details'&gt;Implementation Details&lt;/h2&gt;

&lt;p&gt;For a simple app, say with a single &amp;#8220;unlock app&amp;#8221; kind of in-app purchase, it would be easy to handle the various use cases:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;If the app is already unlocked, we don&amp;#8217;t even need to show the &amp;#8220;Restore&amp;#8221; button. Easy!&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;If the app hasn&amp;#8217;t been unlocked and we receive the &lt;code&gt;paymentQueue:restoreCompletedTransactionsFailedWithError:&lt;/code&gt; message, show an error alert to the user.&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;If the app hasn&amp;#8217;t been unlocked, we receive the &lt;code&gt;paymentQueueRestoreCompletedTransactionsFinished:&lt;/code&gt; message, and the app &lt;strong&gt;still&lt;/strong&gt; isn&amp;#8217;t unlocked, show a &amp;#8220;Sorry, no previous purchases could be restored&amp;#8221; kind of message.&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;If the app hasn&amp;#8217;t been unlocked, we receive the &lt;code&gt;paymentQueueRestoreCompletedTransactionsFinished:&lt;/code&gt; message, and the app &lt;strong&gt;is now unlocked&lt;/strong&gt;, show a &amp;#8220;Restore successful!&amp;#8221; kind of message.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id='in_closing'&gt;In Closing&lt;/h2&gt;

&lt;p&gt;Apps with more complicated IAP usage might need more complicated IAP restore procedures, but I hope this is a good start.&lt;/p&gt;

&lt;p&gt;Share your own IAP restore success and failure stories in the comments below!&lt;/p&gt;</content>
  </entry>
  <entry>
    <title>Simple iOS audio playback</title>
    <link rel="alternate" href="/blog/simple-audio/"/>
    <id>/blog/simple-audio/</id>
    <published>2012-07-05T00:00:00Z</published>
    <updated>2012-07-05T00:00:00Z</updated>
    <author>
      <name>Greg Heo</name>
    </author>
    <content type="html">&lt;p&gt;So you want some sound playback in your iOS app? Just something simple, like an alert sound or two&amp;#8230;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; &lt;em&gt;This post has been slightly tweaked to be ARC-friendly.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id='audio_services'&gt;Audio Services&lt;/h2&gt;

&lt;p&gt;The (arguably) simplest way to play a sound is with &lt;a href='http://developer.apple.com/library/ios/#documentation/AudioToolbox/Reference/SystemSoundServicesReference/Reference/reference.html' title='System Sound Services Reference'&gt;Audio Services&lt;/a&gt;. You can play uncompressed audio files with a maximum of 30 seconds in caf, aif, or wav format. Only one sound can be played at a time.&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s the setup code to load the sound file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// need this include file and the AudioToolbox framework
#import &amp;lt;AudioToolbox/AudioToolbox.h&amp;gt;

// also need an instance variable like so:
// SystemSoundID sound1;

NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@&amp;quot;sample&amp;quot;
                                          withExtension:@&amp;quot;caf&amp;quot;];
AudioServicesCreateSystemSoundID((CFURLRef)soundURL, &amp;amp;sound1);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you like, you can add a callback function for when the sound starts playing:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;AudioServicesAddSystemSoundCompletion(sound1,
                                      NULL,
                                      NULL,
                                      systemAudioCallback,
                                      NULL);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;AudioServicesPlaySystemSound&lt;/code&gt; will play a specified sound; &lt;code&gt;AudioServicesPlayAlertSound&lt;/code&gt; will play the sound and vibrate the device, if applicable:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;AudioServicesPlaySystemSound(sound1); // or...
AudioServicesPlayAlertSound(sound1);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that these functions will return immediately regardless of how long the sound is. You need to have set up the callback and registered it in advance. Here&amp;#8217;s what the callback looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;void systemAudioCallback(SystemSoundID soundId, void *clientData)
{
    NSLog(@&amp;quot;System sound finished playing!&amp;quot;);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Finally, the cleanup:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;AudioServicesRemoveSystemSoundCompletion(sound1);    
AudioServicesDisposeSystemSoundID(sound1);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I say Audio Services is arguably simple because it exposes a C API. People who like objects and square brackets may be mystified by the toll-free bridging and Core Foundation use.&lt;/p&gt;

&lt;p&gt;Why to use it: It&amp;#8217;s simple!&lt;/p&gt;

&lt;p&gt;Why not to use it: It&amp;#8217;s too simple! And based on C/Core Foundation.&lt;/p&gt;

&lt;h2 id='avaudioplayer'&gt;AVAudioPlayer&lt;/h2&gt;

&lt;p&gt;Next is &lt;a href='http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html#//apple_ref/occ/cl/AVAudioPlayer' title='AVAudioPlayer Reference'&gt;AVAudioPlayer&lt;/a&gt;. AVAudioPlayer offers a friendly Objective-C layer where each sound gets its own AVAudioPlayer instance. Audio files can be a wider variety of types, such as compressed caf or mp3.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// need this include file and the AVFoundation framework
#import &amp;lt;AVFoundation/AVFoundation.h&amp;gt;

// also need an instance variable like so:
// AVAudioPlayer *avSound

NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@&amp;quot;sample&amp;quot;
                                          withExtension:@&amp;quot;caf&amp;quot;];
avSound = [[AVAudioPlayer alloc] 
           initWithContentsOfURL:soundURL error:nil];

[avSound play];

// later...

if ([avSound isPlaying])
    [avSound stop];&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The all-important cleanup, if you&amp;#8217;re not using ARC:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[avSound release];&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With AVAudioPlayer, you can set up multiple instances and have playback control over each sound individually. There&amp;#8217;s also much more control over playback settings (volume, panning) and control (play, pause, seek to a point in the audio file).&lt;/p&gt;

&lt;p&gt;AVAudioPlayer has a &lt;a href='http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAudioPlayerDelegateProtocolReference/Reference/Reference.html' title='AVAudioPlayerDelegate protocol reference'&gt;set of delegate methods&lt;/a&gt; to notify you when playback has finished or in the case of interruptions. These follow the usual delegate/protocol patterns found elsewhere in Cocoa.&lt;/p&gt;

&lt;p&gt;You&amp;#8217;ll also get a bit of a delay the first time you play a sound since iOS does a little lazy loading. You can send the &lt;code&gt;prepareToPlay&lt;/code&gt; message to an AVAudioPlayer instance to speed up the eventual &lt;code&gt;play&lt;/code&gt; call.&lt;/p&gt;

&lt;p&gt;Why to use it: It&amp;#8217;s a simple yet powerful object-based system.&lt;/p&gt;

&lt;p&gt;Why not to use it: Latency.&lt;/p&gt;

&lt;h2 id='next'&gt;Next&lt;/h2&gt;

&lt;p&gt;There&amp;#8217;s still some pretty noticeable latency when using AVAudioPlayer; it might be OK for simple sound effects but what if you want more precise and timely playback? Stay tuned for part two, featuring an introduction to OpenAL!&lt;/p&gt;</content>
  </entry>
  <entry>
    <title>Blocks in Objective-C</title>
    <link rel="alternate" href="/blog/blocks-intro/"/>
    <id>/blog/blocks-intro/</id>
    <published>2011-07-12T00:00:00Z</published>
    <updated>2011-07-12T00:00:00Z</updated>
    <author>
      <name>Greg Heo</name>
    </author>
    <content type="html">&lt;p&gt;I gave a quick introductory talk about blocks in Objective-C for iOS and Mac development tonight, and I thought I would put together some of the slides and my notes here as a post.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h2 id='the_least_you_need_to_know'&gt;The least you need to know&lt;/h2&gt;

&lt;p&gt;Blocks are like closures. Or function pointers. Or lambdas. They&amp;#8217;re available starting in OS X 10.6 Snow Leopard and iOS 4.&lt;/p&gt;

&lt;p&gt;The symbol for blocks is this: &lt;code&gt;^&lt;/code&gt; That&amp;#8217;s a reasonable ASCII approximation of the real Greek lambda (upper case Λ, lower case λ).&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s a really simple block, the requisite &amp;#8220;Hello world&amp;#8221;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;^{ NSLog(@&amp;quot;Hello, world!&amp;quot;); };&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Of course, that won&amp;#8217;t actually do anything; it&amp;#8217;s like declaring a function and not calling it. So here&amp;#8217;s the revised version:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;void (^myBlock)() = ^{
    NSLog(@&amp;quot;Hello, world!&amp;quot;);
};
myBlock();&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Block declarations look very much like function pointers, if you have dealt with those in C. In our example here:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;void&lt;/code&gt; is the return type&lt;/li&gt;

&lt;li&gt;^ indicates it&amp;#8217;s a block&lt;/li&gt;

&lt;li&gt;&lt;code&gt;myBlock&lt;/code&gt; is the name of the variable&lt;/li&gt;

&lt;li&gt;the () means it doesn&amp;#8217;t take any arguments; we could also write &lt;code&gt;(void)&lt;/code&gt;&lt;/li&gt;

&lt;li&gt;note that blocks are C statements, so the closing brace is followed by a semicolon.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id='blocks_for_enumeration'&gt;Blocks for enumeration&lt;/h2&gt;

&lt;p&gt;Here&amp;#8217;s our case study, a classic map (as in map/reduce): we have an array of a million objects. We need to iterate through the array and do some work for each array element.&lt;/p&gt;

&lt;p&gt;We could use a for loop or NSEnumerator. In the more recent runtime, we might use fast enumeration like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSArray *collection = [[NSArray alloc] ...];
for (id object in collection) {
    // do something here
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here&amp;#8217;s the block way of doing it. We put the block code directly inline, although you can set up a block variable in advance if you like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    // do something
 }];&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For the block function&amp;#8217;s arguments:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;obj&lt;/code&gt; is the value from the array&lt;/li&gt;

&lt;li&gt;&lt;code&gt;idx&lt;/code&gt; is the array index&lt;/li&gt;

&lt;li&gt;&lt;code&gt;*stop&lt;/code&gt; is used if you need to exit early; set &lt;code&gt;*stop&lt;/code&gt; to &lt;code&gt;YES&lt;/code&gt; to break out of the loop/iteration&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id='concurrency'&gt;Concurrency&lt;/h2&gt;

&lt;p&gt;Blocks are a natural gateway to Grand Central Dispatch (GCD) and being able to take advantage of parallelism, whether through multi-cores, multi-processors, or multi-threads. If it&amp;#8217;s OK to iterate through the collection in parallel and out of order:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[myArray enumerateObjectsWithOptions:NSEnumerationConcurrent
  usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    // do something
 }];&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So there&amp;#8217;s nothing about blocks themselves that speeds up your code. What they offer is a very easy way to segment bits of hard-working code and then lean on GCD to handle the dispatching.&lt;/p&gt;

&lt;h2 id='further_reading'&gt;Further reading&lt;/h2&gt;

&lt;p&gt;There are a lot of topics such as block variables and memory management that are explained far better and in more detail than I could provide. Here are some links:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href='http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html'&gt;&amp;#8220;Blocks&amp;#8221;, Apple developer reference&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;&lt;a href='http://jonmsterling.com/2010/03/28/advanced-blocks-in-objective-c.html'&gt;Advanced blocks in Objective-C&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;&lt;a href='http://cocoasamurai.blogspot.com/2009/09/guide-to-blocks-grand-central-dispatch.html'&gt;Blocks &amp;#38; Grand Central Dispatch&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;&lt;a href='http://clang.llvm.org/docs/BlockLanguageSpec.txt'&gt;Language specification for Blocks (clang/llvm documentation)&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;&lt;a href='http://www.dizzey.com/development/ios/simple-uiview-transitions-animation-using-blocks-in-ios-4/'&gt;UIView transitions animation using blocks&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content>
  </entry>
  <entry>
    <title>Foreign keys - an introduction</title>
    <link rel="alternate" href="/blog/foreign-keys-intro/"/>
    <id>/blog/foreign-keys-intro/</id>
    <published>2011-02-22T00:00:00Z</published>
    <updated>2011-02-22T00:00:00Z</updated>
    <author>
      <name>Greg Heo</name>
    </author>
    <content type="html">&lt;p&gt;Someone recently asked me why I had all these foreign keys defined in the database schema even though &amp;#8220;MySQL doesn&amp;#8217;t support foreign keys.&amp;#8221; After I finished laughing, the statement changed to &amp;#8220;foreign keys aren&amp;#8217;t needed in &lt;em&gt;real&lt;/em&gt; database design anyway.&amp;#8221;&lt;/p&gt;

&lt;p&gt;I laughed again. Then I cried a little. Then I revoked this person&amp;#8217;s license to work in any technical field.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h2 id='a_scenario'&gt;A scenario&lt;/h2&gt;

&lt;p&gt;Let&amp;#8217;s start with the problem that is solved by foreign keys.&lt;/p&gt;

&lt;p&gt;You have a database keeping track of employees. There&amp;#8217;s a table listing all employees, a table with a list of skills, and another table establishing a many-to-many relationship between employees and skills. So Bob knows C++ and Java while James knows C and C++.&lt;/p&gt;

&lt;p&gt;These are all keyed by ID of course, so Bob&amp;#8217;s employee ID is 15 and C++ is actually skill ID 75. That means the employee skills table is filled with numbers since it relates an employee ID to a skill ID.&lt;/p&gt;

&lt;p&gt;Now there&amp;#8217;s a bug in the front-end interface that mangles these IDs. The system tries to insert a new record to relate employee 15 to skill 99; the problem is there is no skill 99. What happens now?&lt;/p&gt;

&lt;p&gt;Or, someone goes right into the database and decides that Java is worthless. She deletes Java from the skills table, but what happens to all those records in the skills-to-employees table that are referencing Java?&lt;/p&gt;

&lt;h2 id='foreign_keys_are_constraints'&gt;Foreign keys are constraints&lt;/h2&gt;

&lt;p&gt;You may have already heard about unique keys, like primary keys. That means values &lt;strong&gt;must&lt;/strong&gt; be unique. The constraint on the field means there can only be one record with a certain value at a time. With a unique key, the database system checks the table when a new record is inserted to enforce the rule.&lt;/p&gt;

&lt;p&gt;A foreign key is another kind of constraint. It&amp;#8217;s called &amp;#8220;foreign&amp;#8221; because it depends on some other table. In our skills and employees example, the skills-to-employees table would have a foreign key constraint linking back to the employee table and the skills table:&lt;/p&gt;
&lt;p style='text-align: center;'&gt;&lt;img alt='SQL table diagram' height='278' src='/images/blog/employees1.png' title='employees1' width='496' /&gt;&lt;/p&gt;
&lt;h2 id='the_result'&gt;The result&lt;/h2&gt;

&lt;p&gt;With foreign keys in place, the system maintains data consistency. If 5 employees have Java listed as a skill, the system will not allow Java to be deleted from the skills table. If there is no skill #99 or there is no employee #101, the system will return an error if you try to insert it into the skills-to-employees table. The insert/delete/update statement is stopped right at the database level.&lt;/p&gt;

&lt;h2 id='the_code'&gt;The code&lt;/h2&gt;

&lt;p&gt;Here&amp;#8217;s how it looks when you&amp;#8217;re creating a new table. Like other kinds of keys, you can specify the foreign key with the field itself (as with &lt;code&gt;employee_id&lt;/code&gt;) or as its own declaration (as with &lt;code&gt;skill_id&lt;/code&gt;):&lt;/p&gt;
&lt;pre&gt;&lt;code class='lang-sql'&gt;CREATE TABLE employee_skills (
    employee_id INTEGER REFERENCES employees(employee_id),
    skill_id INTEGER,
    FOREIGN KEY (skill_id) REFERENCES skills(skill_id),
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And here&amp;#8217;s how it looks when you&amp;#8217;re modifying an existing table:&lt;/p&gt;
&lt;pre&gt;&lt;code class='lang-sql'&gt;ALTER TABLE employee_skills 
    ADD FOREIGN KEY (skill_id) REFERENCES skills(skill_id);
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id='further_reading'&gt;Further reading&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href='http://en.wikipedia.org/wiki/Foreign_key'&gt;Foreign keys on Wikipedia&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;&lt;a href='http://www.postgresql.org/docs/8.1/static/ddl-constraints.html#DDL-CONSTRAINTS-FK'&gt;PostgreSQL documentation&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;&lt;a href='http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-foreign-keys.html'&gt;MySQL documentation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content>
  </entry>
  <entry>
    <title>Schwartzian transform in PHP</title>
    <link rel="alternate" href="/blog/schwartzian-transform/"/>
    <id>/blog/schwartzian-transform/</id>
    <published>2010-05-03T00:00:00Z</published>
    <updated>2010-05-03T00:00:00Z</updated>
    <author>
      <name>Greg Heo</name>
    </author>
    <content type="html">&lt;p&gt;Ah, the &lt;a href='http://en.wikipedia.org/wiki/Schwartzian_transform'&gt;Schwartzian transform&lt;/a&gt;. Is there some way to do this in PHP, that is &amp;#8220;speak PHP with a Lisp&amp;#8221;?&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h2 id='use_the_schwartz_luke'&gt;Use the Schwartz, Luke&lt;/h2&gt;

&lt;p&gt;Let&amp;#8217;s say we have an array of thousands of things, numbers in this case:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$array = array();
for ($i=0; $i &amp;lt; 100000; $i++) {
  $array[] = $i;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For some reason, we want to sort this array by each array element&amp;#8217;s MD5 hash. Here&amp;#8217;s the naïve PHP sort:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function custom_sort($a, $b) {
  return strcmp(md5($a), md5($b));
}
usort($array, &amp;#39;custom_sort&amp;#39;);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In PHP 5.3 and above, we could use a closure. Otherwise, &lt;code&gt;create_function()&lt;/code&gt; does almost the same thing very succinctly:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;usort($array, create_function(&amp;#39;$a,$b&amp;#39;, &amp;#39;return strcmp(md5($a), md5($b));&amp;#39;));&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now that I know how to &lt;a href='http://node79.com/blog/benchmarking-php/'&gt;benchmark PHP&lt;/a&gt;, I wanted some timings to compare. Here on my traveling laptop (a trusty old Powerbook G4 1.5GHz) the sort takes about 33 seconds.&lt;/p&gt;

&lt;h2 id='decoratesortundecorate'&gt;Decorate-sort-undecorate&lt;/h2&gt;

&lt;p&gt;The point of the Schwartzian transform is to perform the expensive operation (the MD5 hash) just once per object. Here&amp;#8217;s how it looks in PHP:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// decorate
array_walk($array, create_function(&amp;#39;&amp;amp;$v, $k&amp;#39;, &amp;#39;$v = array($v, md5($v));&amp;#39;));
// sort
usort($array, create_function(&amp;#39;$a,$b&amp;#39;, &amp;#39;return strcmp($a[1], $b[1]);&amp;#39;));
// undecorate
array_walk($array, create_function(&amp;#39;&amp;amp;$v, $k&amp;#39;, &amp;#39;$v = $v[0];&amp;#39;));&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It doesn&amp;#8217;t look all nicely chained together as it does in Perl, but it works.&lt;/p&gt;

&lt;p&gt;How&amp;#8217;s the timing? 15 seconds, a more than 50% reduction!&lt;/p&gt;

&lt;h2 id='how_it_works'&gt;How it works&lt;/h2&gt;

&lt;p&gt;PHP&amp;#8217;s little-used &lt;code&gt;array_walk()&lt;/code&gt; takes the place of Perl&amp;#8217;s &lt;code&gt;map&lt;/code&gt;: it performs some action on every element in an array. If you pass in an array reference (&lt;code&gt;&amp;amp;$v&lt;/code&gt; rather than plain old &lt;code&gt;$v&lt;/code&gt;) you can also edit the array elements in-place.&lt;/p&gt;

&lt;p&gt;Have a look at the &lt;a href='http://php.net/manual/en/function.array-walk.php'&gt;array_walk()&lt;/a&gt; documentation for more details.&lt;/p&gt;

&lt;p&gt;Useful? Got a better way to do it? Share!&lt;/p&gt;</content>
  </entry>
  <entry>
    <title>Benchmarking PHP</title>
    <link rel="alternate" href="/blog/benchmarking-php/"/>
    <id>/blog/benchmarking-php/</id>
    <published>2010-04-22T00:00:00Z</published>
    <updated>2010-04-22T00:00:00Z</updated>
    <author>
      <name>Greg Heo</name>
    </author>
    <content type="html">&lt;p&gt;I recently needed some quick code timing information so I wrapped some function calls with &lt;code&gt;$current = time()&lt;/code&gt; and then subtracted the results. Then I tried it with &lt;code&gt;microtime()&lt;/code&gt; instead. Then I decided to browse PEAR for some kind of benchmarking tool.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Here are some notes on what &lt;a href='http://pear.php.net/package/Benchmark'&gt;PEAR&amp;#8217;s Benchmark&lt;/a&gt; has to offer.&lt;/p&gt;

&lt;h2 id='iterate'&gt;Iterate&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Benchmark_Iterate&lt;/code&gt; is the classic &amp;#8220;run something n number of times&amp;#8221; kind of benchmark. It returns the time each execution took as well as the mean.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require_once &amp;#39;Benchmark/Iterate.php&amp;#39;;

function doSomething($arg)
{  
    return $arg += 100;
}

$benchmark = new Benchmark_Iterate;
$benchmark-&amp;gt;run(100000, &amp;#39;doSomething&amp;#39;, 100);
$results = $benchmark-&amp;gt;get();&lt;/code&gt;&lt;/pre&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;$results[&amp;#39;iterations&amp;#39;]&lt;/code&gt; returns the number of iterations (100000 in this case)&lt;/li&gt;

&lt;li&gt;&lt;code&gt;$results[&amp;#39;mean&amp;#39;]&lt;/code&gt; returns the mean iteration time&lt;/li&gt;

&lt;li&gt;In this case, there will also be &lt;code&gt;$results[1]&lt;/code&gt; through to &lt;code&gt;$results[100000]&lt;/code&gt; with each individual iteration time. Note the indexes go from 1 to n, &lt;strong&gt;not&lt;/strong&gt; 0 to n-1&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id='timer'&gt;Timer&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Benchmark_Timer&lt;/code&gt; allows you to set markers at various points in your code. It keeps track of the time elapsed between markers as my original &lt;code&gt;time()&lt;/code&gt; and &lt;code&gt;microtime()&lt;/code&gt; example did.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require_once &amp;#39;Benchmark/Timer.php&amp;#39;;

$timer = new Benchmark_Timer();

$timer-&amp;gt;setMarker(&amp;#39;start work&amp;#39;);
for ($i=0; $i &amp;lt; 100000; $i++) {
  $a = sprintf(&amp;quot;%.2f&amp;quot;, $i);
}
$timer-&amp;gt;setMarker(&amp;#39;end word&amp;#39;);

$results = $timer-&amp;gt;getProfiling();
$timer-&amp;gt;display();&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;display()&lt;/code&gt; method will print out a table with your results. Or, you can access the raw results with &lt;code&gt;getProfiling()&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id='profiler'&gt;Profiler&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Benchmark_Profiler&lt;/code&gt; is similar to &lt;code&gt;Benchmark_Timer&lt;/code&gt; except it&amp;#8217;s meant to be enclosed in function and methods. You can also nest various things.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require_once &amp;#39;Benchmark/Profiler.php&amp;#39;;
$profiler = new Benchmark_Profiler();

$profiler-&amp;gt;start();
doSomething();
doSomethingElse();

$profiler-&amp;gt;stop();
$profiler-&amp;gt;output();&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Not as simple as that though; doSomething() and doSomethingElse() look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function doSomething() {
    global $profiler;
    
    $profiler-&amp;gt;enterSection(&amp;#39;doSomething&amp;#39;);
    // do lots of work
    $profiler-&amp;gt;leaveSection(&amp;#39;doSomething&amp;#39;);
}

function doSomethingElse() {
    global $profiler;
    
    $profiler-&amp;gt;enterSection(&amp;#39;doSomethingElse&amp;#39;);
    doSomething();
    // do even more work
    $profiler-&amp;gt;leaveSection(&amp;#39;doSomethingElse&amp;#39;);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note the nested call in doSomethingElse(). &lt;code&gt;Benchmark_Profiler&lt;/code&gt; will handle this correctly and show the profile results as expected.&lt;/p&gt;

&lt;p&gt;As with &lt;code&gt;Benchmark_Timer&lt;/code&gt;, the &lt;code&gt;output()&lt;/code&gt; method will print out a table with your results. You can get at the data for a particular section by passing the section name to &lt;code&gt;getSectionInformations()&lt;/code&gt; or data for all sections with &lt;code&gt;getAllSectionsInformations()&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id='thats_it'&gt;That&amp;#8217;s it&lt;/h2&gt;

&lt;p&gt;Remember, profile before optimizing.&lt;/p&gt;</content>
  </entry>
  <entry>
    <title>SQL JOINs, part 2</title>
    <link rel="alternate" href="/blog/sql-join-2/"/>
    <id>/blog/sql-join-2/</id>
    <published>2010-02-19T00:00:00Z</published>
    <updated>2010-02-19T00:00:00Z</updated>
    <author>
      <name>Greg Heo</name>
    </author>
    <content type="html">&lt;p&gt;&lt;a href='/blog/sql-join-1/'&gt;Last time&lt;/a&gt;, we started our discussion of SQL joins and covered the common cases: LEFT, INNER, and RIGHT. Today, we&amp;#8217;ll cover the lesser-used CROSS and OUTER joins.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h2 id='the_outer_limits'&gt;The OUTER limits&lt;/h2&gt;

&lt;p&gt;Here&amp;#8217;s a sample data set:&lt;/p&gt;
&lt;div class='clear' style='width: 100%;'&gt;
&lt;div style='float: left; padding-right: 2em;'&gt;
&lt;table class='nice'&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;td class='title' colspan='2'&gt;Products&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;th&gt;Product ID&lt;/th&gt;&lt;th&gt;Product name&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;100&lt;/td&gt;&lt;td&gt;Pencil&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;101&lt;/td&gt;&lt;td&gt;Pen&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;103&lt;/td&gt;&lt;td&gt;Paperclips&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;

&lt;div style='float: left;'&gt;
&lt;table class='nice'&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;td class='title' colspan='2'&gt;Prices&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;th&gt;Product ID&lt;/th&gt;&lt;th&gt;Product price&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;100&lt;/td&gt;&lt;td&gt;0.25&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;101&lt;/td&gt;&lt;td&gt;0.40&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;102&lt;/td&gt;&lt;td&gt;0.75&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;br clear='all' /&gt;
&lt;/div&gt;
&lt;p&gt;Let&amp;#8217;s review some things from last week. The directional joins (LEFT and RIGHT) mark one table as the primary one. INNER join is like a conjunction of left and right where the record and join have to exist in both tables.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT * FROM products
INNER JOIN prices ON (products.product_id=prices.product_id)&lt;/code&gt;&lt;/pre&gt;
&lt;table class='nice'&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Product ID&lt;/th&gt;&lt;th&gt;Product name&lt;/th&gt;&lt;th&gt;Product ID&lt;/th&gt;&lt;th&gt;Product Price&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tr&gt;&lt;td&gt;100&lt;/td&gt;&lt;td&gt;Pencil&lt;/td&gt;&lt;td&gt;100&lt;/td&gt;&lt;td&gt;0.25&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;101&lt;/td&gt;&lt;td&gt;Pen&lt;/td&gt;&lt;td&gt;101&lt;/td&gt;&lt;td&gt;0.40&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;OUTER join is like saying &amp;#8220;either LEFT or RIGHT&amp;#8221; (a &amp;#8220;disjunction&amp;#8221; in tech-speak). The result set will contain data from either just the left table, just the right, or both:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT * FROM products
OUTER JOIN prices ON (products.product_id=prices.product_id)&lt;/code&gt;&lt;/pre&gt;
&lt;table class='nice'&gt;
&lt;tr&gt;&lt;th&gt;Product ID&lt;/th&gt;&lt;th&gt;Product name&lt;/th&gt;&lt;th&gt;Product ID&lt;/th&gt;&lt;th&gt;Product Price&lt;/th&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;100&lt;/td&gt;&lt;td&gt;Pencil&lt;/td&gt;&lt;td&gt;100&lt;/td&gt;&lt;td&gt;0.25&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;101&lt;/td&gt;&lt;td&gt;Pen&lt;/td&gt;&lt;td&gt;101&lt;/td&gt;&lt;td&gt;0.40&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;NULL&lt;/td&gt;&lt;td&gt;NULL&lt;/td&gt;&lt;td&gt;102&lt;/td&gt;&lt;td&gt;0.75&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;103&lt;/td&gt;&lt;td&gt;Paperclips&lt;/td&gt;&lt;td&gt;NULL&lt;/td&gt;&lt;td&gt;NULL&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;Notice we get a full set of four records. For products 100 and 101 we have a full set of information: ID, name, price. Product 102 looks like a RIGHT join with just a price and NULL for the name. Product 103 looks like a LEFT join with a name and no price.&lt;/p&gt;

&lt;h2 id='cross_combinations'&gt;CROSS Combinations&lt;/h2&gt;

&lt;p&gt;We&amp;#8217;re back at the beginning in a way: a cross join is really the mother of all joins. Let&amp;#8217;s look at an example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT * FROM products CROSS JOIN prices;&lt;/code&gt;&lt;/pre&gt;
&lt;table class='nice'&gt;
&lt;tr&gt;&lt;th&gt;Product ID&lt;/th&gt;&lt;th&gt;Product name&lt;/th&gt;&lt;th&gt;Product ID&lt;/th&gt;&lt;th&gt;Product Price&lt;/th&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;100&lt;/td&gt;&lt;td&gt;Pencil&lt;/td&gt;&lt;td&gt;100&lt;/td&gt;&lt;td&gt;0.25&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;100&lt;/td&gt;&lt;td&gt;Pencil&lt;/td&gt;&lt;td&gt;101&lt;/td&gt;&lt;td&gt;0.40&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;100&lt;/td&gt;&lt;td&gt;Pencil&lt;/td&gt;&lt;td&gt;102&lt;/td&gt;&lt;td&gt;0.75&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;101&lt;/td&gt;&lt;td&gt;Pen&lt;/td&gt;&lt;td&gt;100&lt;/td&gt;&lt;td&gt;0.25&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;101&lt;/td&gt;&lt;td&gt;Pen&lt;/td&gt;&lt;td&gt;101&lt;/td&gt;&lt;td&gt;0.40&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;101&lt;/td&gt;&lt;td&gt;Pen&lt;/td&gt;&lt;td&gt;102&lt;/td&gt;&lt;td&gt;0.75&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td colspan='4'&gt;. . .&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;That&amp;#8217;s just a snippet from the results. Note that every record in the left table will be joined to every record in the right table.&lt;/p&gt;

&lt;p&gt;Why is this useful? It&amp;#8217;s the first step to the other joins. To turn these results into an inner join, for example, we just need to match up the two product IDs and discard the rows where the IDs don&amp;#8217;t match.&lt;/p&gt;

&lt;p&gt;That sounds useful for the SQL engine itself, but what about useful to humans? Let&amp;#8217;s say you have one table listing every entree available at a restaurant and another table listing all the wines. Wouldn&amp;#8217;t it be nice to pull out a list of every entree + wine combination? Yes it would!&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT * FROM entrees CROSS JOIN wines;&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id='in_closing'&gt;In Closing&lt;/h2&gt;

&lt;p&gt;That concludes our discussion of SQL JOINs. Let&amp;#8217;s hear your own JOIN tips and horror stories!&lt;/p&gt;</content>
  </entry>
  <entry>
    <title>SQL JOINs, part 1</title>
    <link rel="alternate" href="/blog/sql-join-1/"/>
    <id>/blog/sql-join-1/</id>
    <published>2010-02-16T00:00:00Z</published>
    <updated>2010-02-16T00:00:00Z</updated>
    <author>
      <name>Greg Heo</name>
    </author>
    <content type="html">&lt;p&gt;SQL JOIN is right up there in the list of most useful inventions along with sliced bread, the iPhone, and the chemical toilet. Why are there so many different kinds? Left? Right? Outer? Let&amp;#8217;s review.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h2 id='the_inner_track'&gt;The INNER track&lt;/h2&gt;

&lt;p&gt;Here&amp;#8217;s our example data set:&lt;/p&gt;
&lt;div class='clear' style='width: 100%;'&gt;
&lt;div style='float: left; padding-right: 2em;'&gt;
&lt;table class='nice'&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;td class='title' colspan='2'&gt;Equipment&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;th&gt;Item&lt;/th&gt;&lt;th&gt;Owner&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;iPhone&lt;/td&gt;&lt;td&gt;Jim&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Stapler&lt;/td&gt;&lt;td&gt;Dwight&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Calculator&lt;/td&gt;&lt;td&gt;Jim&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Printer&lt;/td&gt;&lt;td&gt;Pam&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Microwave&lt;/td&gt;&lt;td&gt;Everyone&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;

&lt;div style='float: left;'&gt;
&lt;table class='nice'&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;td class='title' colspan='2'&gt;People&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;th&gt;Name&lt;/th&gt;&lt;th&gt;Extension&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Jim&lt;/td&gt;&lt;td&gt;255&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Dwight&lt;/td&gt;&lt;td&gt;132&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Michael&lt;/td&gt;&lt;td&gt;329&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Pam&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;br clear='all' /&gt;
&lt;/div&gt;
&lt;p&gt;That&amp;#8217;s some pretty crappy schema design. Anyway, we want a list of equipment along with its owner and that person&amp;#8217;s telephone extension:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT * FROM equipment JOIN people ON (people.name=equipment.owner)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The result set will look something like this:&lt;/p&gt;
&lt;div class='clear'&gt;
&lt;table class='nice'&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;iPhone&lt;/td&gt;&lt;td&gt;Jim&lt;/td&gt;&lt;td&gt;Jim&lt;/td&gt;&lt;td&gt;255&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Stapler&lt;/td&gt;&lt;td&gt;Dwight&lt;/td&gt;&lt;td&gt;Dwight&lt;/td&gt;&lt;td&gt;132&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Calculator&lt;/td&gt;&lt;td&gt;Jim&lt;/td&gt;&lt;td&gt;Jim&lt;/td&gt;&lt;td&gt;255&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Printer&lt;/td&gt;&lt;td&gt;Pam&lt;/td&gt;&lt;td&gt;Pam&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;Hey, what happened to the microwave? The SELECT picks it up since it&amp;#8217;s in the equipment table, but there&amp;#8217;s no matching record in the people table (there&amp;#8217;s no person called &amp;#8220;Everyone&amp;#8221;).&lt;/p&gt;

&lt;p&gt;When you say JOIN, that actually means INNER JOIN, which means &amp;#8220;if you cannot find a matching record to join, discard it&amp;#8221;. And there goes the microwave.&lt;/p&gt;

&lt;p&gt;In this case, that might not be what we&amp;#8217;re interested in. Maybe we want to know about all the equipment we have, and the owners are just nice to know.&lt;/p&gt;

&lt;h2 id='enter_stage_left'&gt;Enter stage LEFT&lt;/h2&gt;

&lt;p&gt;LEFT JOIN is what we want in this case:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT * FROM equipment LEFT JOIN people ON (people.name=equipment.owner)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice that our main table &lt;code&gt;equipment&lt;/code&gt; is on the left side of the statement, and our joined table &lt;code&gt;people&lt;/code&gt; is toward the right. A left join means &amp;#8220;return every record available from the table on the left, even if there&amp;#8217;s nothing to join to&amp;#8221;. Here are the results:&lt;/p&gt;
&lt;div class='clear'&gt;
&lt;table class='nice'&gt;
&lt;tr&gt;&lt;td&gt;iPhone&lt;/td&gt;&lt;td&gt;Jim&lt;/td&gt;&lt;td&gt;Jim&lt;/td&gt;&lt;td&gt;255&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Stapler&lt;/td&gt;&lt;td&gt;Dwight&lt;/td&gt;&lt;td&gt;Dwight&lt;/td&gt;&lt;td&gt;132&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Calculator&lt;/td&gt;&lt;td&gt;Jim&lt;/td&gt;&lt;td&gt;Jim&lt;/td&gt;&lt;td&gt;255&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Printer&lt;/td&gt;&lt;td&gt;Pam&lt;/td&gt;&lt;td&gt;Pam&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Microwave&lt;/td&gt;&lt;td&gt;Everyone&lt;/td&gt;&lt;td&gt;NULL&lt;/td&gt;&lt;td&gt;NULL&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;Much better. We get to see every piece of equipment and the fields that couldn&amp;#8217;t be joined are filled with NULLs.&lt;/p&gt;

&lt;h2 id='exit_stage_right'&gt;Exit stage RIGHT&lt;/h2&gt;

&lt;p&gt;A right join is essentially the same thing except everything from the table on the right is returned. That means these two queries will return the same thing (although the fields may show up in a different order):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT * FROM equipment LEFT JOIN people ON (people.name=equipment.owner)

SELECT * FROM people RIGHT JOIN equipment ON (people.name=equipment.owner)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Generally though, you put the main table as the SELECT and the secondary one as the join. Right joins don&amp;#8217;t get a lot of use and I would even argue that they&amp;#8217;re bad form. Just stick to left joins and your future self and other code maintainers will thank you.&lt;/p&gt;

&lt;h2 id='in_closing'&gt;In closing&lt;/h2&gt;

&lt;p&gt;The default inner join is really a &amp;#8220;left and right&amp;#8221; or &amp;#8220;both&amp;#8221; join, since a record must be returned in both tables. Most JOINs in the world are either INNER or LEFT so those are the ones to know.&lt;/p&gt;

&lt;p&gt;In &lt;a href='/blog/sql-join-2/'&gt;part 2&lt;/a&gt;, we&amp;#8217;ll look at the oddballs: OUTER and CROSS joins.&lt;/p&gt;</content>
  </entry>
  <entry>
    <title>Benchmarking Perl</title>
    <link rel="alternate" href="/blog/benchmarking-perl/"/>
    <id>/blog/benchmarking-perl/</id>
    <published>2009-09-14T00:00:00Z</published>
    <updated>2009-09-14T00:00:00Z</updated>
    <author>
      <name>Greg Heo</name>
    </author>
    <content type="html">&lt;p&gt;After browsing through the Perl documentation and reading &lt;a href='http://perldoc.perl.org/perlperf.html'&gt;perlperf&lt;/a&gt;, I had a sudden urge to profile some code. I&amp;#8217;ve been guilty on many occasions of optimizing before profiling so think of this post as a kind of restitution.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s a trivial piece of code I wrote long ago:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;my $height = sprintf(&amp;quot;%d&amp;#39;%d\&amp;quot;&amp;quot;, $inches / 12, $inches % 12);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Given an inches value of 64, this will make a feet and height string like 5&amp;#8217;4&amp;#8221;.&lt;/p&gt;

&lt;p&gt;The sprintf() call is probably unnecessary and needlessly gives away my C background. I could &amp;#8220;optimize&amp;#8221; the line to this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;my $height = int($inches / 12) . &amp;quot;&amp;#39;&amp;quot; . $inches % 12 . &amp;#39;&amp;quot;&amp;#39;;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That makes the same two calculations (one divide, one modulus) but eliminates the function call. It must be more efficient too, right?&lt;/p&gt;

&lt;p&gt;Finally, here&amp;#8217;s a snippet of code I found online that does the same thing in what I&amp;#8217;m pretty certain is a horrible waste of cycles:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;my $feet_dec = $inches / 12;
my @parts = split(/\./, $feet_dec);

my $feet = $parts[0];
my $fraction = int(((&amp;#39;0.&amp;#39;.$parts[1])*12) + 0.5);

my $height = $feet.&amp;quot;\&amp;#39;&amp;quot;.$fraction.&amp;quot;\&amp;quot;&amp;quot;;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Wow. If that doesn&amp;#8217;t inspire you to fire up the profiler, I don&amp;#8217;t know what will.&lt;/p&gt;

&lt;h2 id='benchmark'&gt;Benchmark&lt;/h2&gt;

&lt;p&gt;Here&amp;#8217;s the code to run things through the &lt;em&gt;Benchmark&lt;/em&gt; module:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;use Benchmark;

timethese(1000, {
  &amp;#39;sprintf&amp;#39; =&amp;gt; sub 
    { for (my $i = 0; $i &amp;lt; 1000; $i++) { inches1($i); } },
  &amp;#39;calc&amp;#39;    =&amp;gt; sub
    { for (my $i = 0; $i &amp;lt; 1000; $i++) { inches2($i); } },
  &amp;#39;long&amp;#39;    =&amp;gt; sub
    { for (my $i = 0; $i &amp;lt; 1000; $i++) { inches3($i); } },
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;inches1, inches2, and inches3 contain the code snippets above. The results:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Benchmark: timing 1000 iterations of calc, long, sprintf...
      calc:  4 wallclock secs ( 3.69 usr +  0.03 sys =  3.72 CPU)
             @ 268.82/s (n=1000)
      long: 19 wallclock secs (16.89 usr +  0.13 sys = 17.02 CPU)
             @ 58.75/s (n=1000)
   sprintf:  4 wallclock secs ( 3.76 usr +  0.02 sys =  3.78 CPU)
             @ 264.55/s (n=1000)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For some reason, I thought the sprintf() call would be much more expensive than it really is. I can continue with my C coding habits after all!&lt;/p&gt;

&lt;p&gt;What&amp;#8217;s so horrible about the &amp;#8216;long&amp;#8217; way of doing things? My guess is the call to split() that&amp;#8217;s taking so much time. I sure wish there were some way to do a line-by-line analysis&amp;#8230;&lt;/p&gt;</content>
  </entry>
</feed>
