<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>VerySimple &#187; SQL</title>
	<atom:link href="http://verysimple.com/category/sql/feed/" rel="self" type="application/rss+xml" />
	<link>http://verysimple.com</link>
	<description>Custom Software</description>
	<lastBuildDate>Fri, 06 Jan 2012 18:12:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Installing LAMP Stack on OSX 10.7 Lion</title>
		<link>http://verysimple.com/2011/08/18/installing-lamp-stack-on-osx-10-7-lion/</link>
		<comments>http://verysimple.com/2011/08/18/installing-lamp-stack-on-osx-10-7-lion/#comments</comments>
		<pubDate>Thu, 18 Aug 2011 22:14:41 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[Apache]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[OSX]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://verysimple.com/?p=998</guid>
		<description><![CDATA[This is a follow-up to my previous article on installing a LAMP Stack on Snow Leopard and explains the steps that you need to get Lion up and running for LAMP development.  (Linux, Apache, MySQL and PHP in case you don&#8217;t already know).  Lion comes pre-installed with Apache and PHP 5.3.6 so you only need [...]]]></description>
			<content:encoded><![CDATA[<p>This is a follow-up to my previous article on <a href="http://verysimple.com/2009/09/18/installing-lamp-stack-on-osx-10-6-snow-leopard/" target="_blank">installing a LAMP Stack on Snow Leopard</a> and explains the steps that you need to get Lion up and running for LAMP development.  (Linux, Apache, MySQL and PHP in case you don&#8217;t already know).  Lion comes pre-installed with Apache and PHP 5.3.6 so you only need to enable those features.  MySQL is the only component that you have to install.</p>
<h3>1.Turn on Apache</h3>
<p>Go to System Settings-&gt;Sharing and turn on Web Sharing. If necessary click the button that says &#8220;Create Home Folder&#8221; which will create a folder called &#8220;Sites&#8221; in your home directory.  You now have a web server that you can access at http://localhost/~username/  (&#8220;username&#8221; being your own account login name)</p>
<h3>2. Edit /private/etc/apache2/httpd.conf</h3>
<p>To enable PHP uncomment (remove the number sign at the beginning of) the line:</p>
<p>#LoadModule php5_module libexec/apache2/libphp5.so</p>
<p>(optional) you can re-map the server root to your home website directory by editing DocumentRoot:</p>
<p>DocumentRoot “/Users/username/Sites”</p>
<p>If you wish to use .htaccess files then look a bit further down AllowOverride and set it to &#8220;All&#8221; like so:</p>
<p>Options FollowSymLinks<br />
AllowOverride All<br />
Order deny,allow<br />
Deny from all</p>
<h3>3. Edit /private/etc/apache2/users/username.conf</h3>
<p>Your user directory has it&#8217;s own permissions as well which are located in this separate file.  You may wish to enable FollowSymLinks and AllowOverride again here by changing these two lines like so:</p>
<p>Options Indexes MultiViews FollowSymLinks<br />
AllowOverride to All</p>
<h3>4. Copy /private/etc/php.ini.default to /private/etc/php.ini</h3>
<p>OSX includes a default php.ini file that you can use but you must rename or copy it first.  If you don&#8217;t do this then PHP will still run but it will just be using the default initialization settings with no way for you to override them.</p>
<p>Edit these settings in <strong>php.ini</strong> (some of these settings will not come into play until they are installed)</p>
<p>display_errors = On<br />
mysql.default_socket = /tmp/mysql.sock<br />
pdo_mysql.default_socket=/tmp/mysql.sock<br />
date.timezone = &#8216;America/Chicago&#8217;<br />
include_path = &#8220;.:/usr/lib/php/pear&#8221;</p>
<h3>5. (Optional) Install PEAR</h3>
<p>If you use the PEAR libraries you can install them using the included phar file like so:</p>
<p>sudo php /usr/lib/php/install-pear-nozlib.phar<br />
sudo pear config-set php_ini /private/etc/php.ini<br />
sudo pecl config-set php_ini /private/etc/php.ini<br />
sudo pear upgrade-all</p>
<h3>6.  Install MySQL</h3>
<p>This doesn&#8217;t really require instructions, simply download the latest MySQL from <a href="http://mysql.com/">mysql.com</a>.  I installed the 32 bit version, however it may be possible to run the 64 bit version as well.</p>
<h3>7. (Optional) Install Apache Plugins</h3>
<p>If you use encryption you may need to install mcrypt.  <a href="http://michaelgracie.com/2011/07/21/plugging-mcrypt-into-php-on-mac-os-x-lion-10-7/" target="_blank">Instructions</a> have been provided by Michael Gracie</p>
<p>If you use the Zend debugger you can install that using <a href="http://verysimple.com/2011/08/16/installing-zend-php-debugger-in-eclipse-on-osx/" target="_blank">these instructions</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://verysimple.com/2011/08/18/installing-lamp-stack-on-osx-10-7-lion/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>MySQL can&#8217;t specify target table for update in FROM clause</title>
		<link>http://verysimple.com/2011/03/30/mysql-cant-specify-target-table-for-update-in-from-clause/</link>
		<comments>http://verysimple.com/2011/03/30/mysql-cant-specify-target-table-for-update-in-from-clause/#comments</comments>
		<pubDate>Wed, 30 Mar 2011 21:50:54 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://verysimple.com/?p=865</guid>
		<description><![CDATA[If you&#8217;re at this page you probably have encountered an error similar to &#8220;Error Code: 1093 You can&#8217;t specify target table &#8216;my_table&#8217; for update in FROM clause&#8221; The reason for this error is that MySQL doesn&#8217;t allow updates to a table when you are also using that same table in an inner select as your [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re at this page you probably have encountered an error similar to &#8220;Error Code: 1093 You can&#8217;t specify target table &#8216;my_table&#8217; for update in FROM clause&#8221;  The reason for this error is that MySQL doesn&#8217;t allow updates to a table when you are also using that same table in an inner select as your update criteria.  I don&#8217;t know why MySQL has this limitation, but my best guess is that it causes some issue due to file locking or perhaps could cause an infinite loop.  Other databases support this type of statement but MySQL requires a workaround.</p>
<p>Luckily there&#8217;s a solution.  As an example below is a query that will set the priority to &#8220;1&#8243; for all customers who have at least one matching purchase record.  <em>I realize this is a stupid way to run this particular query, however I am merely posting a simple example of a query to demonstrate the error and workaround.  Jeez, get off my back!</em></p>
<p><em><span id="more-865"></span></em></p>
<h3>A Non-Working Example:</h3>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">UPDATE</span> customer
<span style="color: #993333; font-weight: bold;">SET</span> customer<span style="color: #66cc66;">.</span>priority <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">1</span>
<span style="color: #993333; font-weight: bold;">WHERE</span> customer<span style="color: #66cc66;">.</span>id <span style="color: #993333; font-weight: bold;">IN</span>
<span style="color: #66cc66;">&#40;</span>
  <span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #993333; font-weight: bold;">DISTINCT</span> customer<span style="color: #66cc66;">.</span>id <span style="color: #993333; font-weight: bold;">FROM</span> customer <span style="color: #993333; font-weight: bold;">INNER</span> <span style="color: #993333; font-weight: bold;">JOIN</span> purchase <span style="color: #993333; font-weight: bold;">ON</span> customer<span style="color: #66cc66;">.</span>id <span style="color: #66cc66;">=</span> purchase<span style="color: #66cc66;">.</span>customer_id
<span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>The above query will give you the MySQL target table error because we are trying to update the customer table, but the customer table is also used to supply the list of IDs.</p>
<h3>A Working Version of the Example Above:</h3>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">UPDATE</span> customer
<span style="color: #993333; font-weight: bold;">SET</span> customer<span style="color: #66cc66;">.</span>priority <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">1</span>
<span style="color: #993333; font-weight: bold;">WHERE</span> customer<span style="color: #66cc66;">.</span>id <span style="color: #993333; font-weight: bold;">IN</span>
<span style="color: #66cc66;">&#40;</span>
  <span style="color: #993333; font-weight: bold;">SELECT</span> id <span style="color: #993333; font-weight: bold;">FROM</span>
  <span style="color: #66cc66;">&#40;</span>
    <span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #993333; font-weight: bold;">DISTINCT</span> customer<span style="color: #66cc66;">.</span>id <span style="color: #993333; font-weight: bold;">FROM</span> customer <span style="color: #993333; font-weight: bold;">INNER</span> <span style="color: #993333; font-weight: bold;">JOIN</span> purchase <span style="color: #993333; font-weight: bold;">ON</span> customer<span style="color: #66cc66;">.</span>id <span style="color: #66cc66;">=</span> purchase<span style="color: #66cc66;">.</span>customer_id
  <span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">AS</span> tmptable
<span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>The query is basically the same, except the inner select is wrapped inside another select.  The most important thing to note is that the original select has been given an alias &#8220;<strong>tmptable</strong>&#8220;.  (The name tmptable is arbitrary, you can give it any alias name.)  The alias is important because assigning one will tell MySQL to create a temporary table from this select query.  The temporary table may then be used as the source criteria for the update statement.</p>
<p>The reason it is wrapped inside another query is because MySQL syntax does not let you assign an alias to a select query when it is part of an update statement.  So we have to put it inside another query which, I suppose separates it from the update statement.</p>
<p>The information about creating the temporary table was borrowed from <a href="http://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/" target="_blank">Xaprb&#8217;s blog</a>, who goes into a little more detail about the mechanics.</p>
]]></content:encoded>
			<wfw:commentRss>http://verysimple.com/2011/03/30/mysql-cant-specify-target-table-for-update-in-from-clause/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>sqlite lpad and rpad functionality</title>
		<link>http://verysimple.com/2010/01/12/sqlite-lpad-rpad-function/</link>
		<comments>http://verysimple.com/2010/01/12/sqlite-lpad-rpad-function/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 04:23:30 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[SQLite]]></category>

		<guid isPermaLink="false">http://www.verysimple.com/blog/?p=483</guid>
		<description><![CDATA[sqlite is missing several basic database features compared to typical SQL servers and unfortunately padding is one of them.  For a most situations though, you can use a simple hack to get the same functionality.   This trick uses a combination of concatenation and substr: -- the statement below is almost the same as -- select [...]]]></description>
			<content:encoded><![CDATA[<p>sqlite is missing several basic database features compared to typical SQL servers and unfortunately padding is one of them.  For a most situations though, you can use a simple hack to get the same functionality.   This trick uses a combination of concatenation and substr:</p>
<pre>-- the statement below is almost the same as
-- select lpad(mycolumn,'0',10) from mytable

select substr('0000000000' || mycolumn, -10, 10) from mytable

-- the statement below is almost the same as
-- select rpad(mycolumn,'0',10) from mytable

select substr(mycolumn || '0000000000', 1, 10) from mytable
</pre>
<p>The statement is fairly self-explanatory, but in case it doesn&#8217;t make sense we&#8217;re simply adding a big long string of characters to the original value and then truncating it down to the desired length.  The string used for concatenation has to be at least the same length that you are padding &#8211; 10 characters is used in this example (&#8217;0000000000&#8242;).</p>
<p>In most cases this workaround produces the same results as lpad/rpad except in the case where the length of your original value is greater than the length that you are padding.  In which case the original value would get truncated.  Usually when you are padding you know what the maximum length of the column anyway.</p>
<p>If you know of a more efficient technique, please post a comment.</p>
]]></content:encoded>
			<wfw:commentRss>http://verysimple.com/2010/01/12/sqlite-lpad-rpad-function/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Installing LAMP stack on OSX 10.6 Snow Leopard</title>
		<link>http://verysimple.com/2009/09/18/installing-lamp-stack-on-osx-10-6-snow-leopard/</link>
		<comments>http://verysimple.com/2009/09/18/installing-lamp-stack-on-osx-10-6-snow-leopard/#comments</comments>
		<pubDate>Fri, 18 Sep 2009 21:55:19 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[OSX]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.verysimple.com/blog/?p=414</guid>
		<description><![CDATA[Updated instructions are available for installing LAMP on OSX 10.7 Lion. I&#8217;m setting up a new machine and found a great tutorial written by Josh Lockhart on getting a PHP web development environment up and running on Snow Leopard.  This goes through almost everything to be up and running for a typical LAMP stack with [...]]]></description>
			<content:encoded><![CDATA[<p>Updated instructions are available for <a href="http://verysimple.com/2011/08/18/installing-lamp-stack-on-osx-10-7-lion/">installing LAMP on OSX 10.7 Lion</a>.</p>
<p>I&#8217;m setting up a new machine and found a great tutorial written by Josh Lockhart on <a href="http://www.newmediacampaigns.com/page/install-pear-phpunit-xdebug-on-macosx-snow-leopard" target="_blank">getting a PHP web development environment up and running on Snow Leopard</a>.  This goes through almost everything to be up and running for a typical LAMP stack with unit testing using all of the default services.</p>
<p>Josh&#8217;s instructions include everything that I need except mcrypt &amp; IMAP.  Luckily Michael Gracie has provided a walk-through for <a href="http://michaelgracie.com/2009/09/23/plugging-mcrypt-into-php-on-mac-os-x-snow-leopard-10.6.1/" target="_blank">installing mcrypt on Snow Leopard</a> which involves re-compiling some things, but isn&#8217;t as tough as it first appears.  A <a href="http://www.activecollab.com/forums/topic/5844/">walk-through for installing IMAP support</a> is available on activeColab (with a pre-built binary).</p>
<p>After getting PHP, mcrypt and IMAP going, the last step for me is setting up MySQL which has some caveats on OSX.  The main problem is that the MySQL installer places the mysql.sock file in a non-standard place and so you have to either <a href="http://www.verysimple.com/blog/2009/01/07/php-on-os-cant-connect-to-local-mysql-server-through-socket-varmysqlmysqlsock/">create a link or alter your php.ini file</a> before PHP will be able to talk to MySQL.  (If you get <em>&#8220;Can’t connect to local MySQL server through socket ‘/var/mysql/mysql.sock’</em>&#8221; or  “<em>No such file or directory</em>” when calling mysql_connect, then this is the problem)</p>
<p><span id="more-414"></span></p>
<p>After completing the steps on Josh&#8217;s &amp; Michael&#8217;s pages and running the MySQL installation package, here are the additional steps that I like to take to get my local environment configured:</p>
<p><strong>Edit /private/etc/php.ini</strong></p>
<p>display_errors = On<br />
mysql.default_socket = /tmp/mysql.sock<br />
pdo_mysql.default_socket=/tmp/mysql.sock<br />
date.timezone = &#8216;America/Chicago&#8217;</p>
<p><strong>Edit /private/etc/apache2/httpd.conf</strong></p>
<p>DocumentRoot &#8220;/Users/jason/Sites&#8221;</p>
<p><strong>Edit /private/etc/apache2/users/jason.conf</strong></p>
<p>Append <em>FollowSymLinks</em> to the Options</p>
<p>Change AllowOverride to All</p>
<p>I also like to change the permissions on php.ini and httpd.conf to allow my user account edit permissions and create an alias to those two files somewhere easy to get to.</p>
<p>Installing <a href="http://www.mamp.info" target="_blank">MAMP</a> is probably easier, but for some reason I prefer using all of the services that are pre-bundled with OSX.  Also Snow Leopard includes PHP 5.3 which led me to find a couple of deprecated functions in some of our libraries.</p>
]]></content:encoded>
			<wfw:commentRss>http://verysimple.com/2009/09/18/installing-lamp-stack-on-osx-10-6-snow-leopard/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>PHP on OSX: Can&#039;t connect to local MySQL server through socket &#039;/var/mysql/mysql.sock&#039;</title>
		<link>http://verysimple.com/2009/01/07/php-on-os-cant-connect-to-local-mysql-server-through-socket-varmysqlmysqlsock/</link>
		<comments>http://verysimple.com/2009/01/07/php-on-os-cant-connect-to-local-mysql-server-through-socket-varmysqlmysqlsock/#comments</comments>
		<pubDate>Wed, 07 Jan 2009 21:59:29 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[*NIX]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[OSX]]></category>

		<guid isPermaLink="false">http://www.verysimple.com/blog/2009/01/07/osx-php-cant-connect-to-local-mysql-server-through-socket-varmysqlmysqlsock/</guid>
		<description><![CDATA[When installing PHP and MySQL on OSX  you may get the error Can&#8217;t connect to local MySQL server through socket &#8216;/var/mysql/mysql.sock&#8217;.  Or you may also get &#8220;No such file or directory&#8221; when calling mysql_connect from a PHP page.  This occurs because PHP is looking for the file mysql.sock in it&#8217;s typical installation location of /var/mysql/mysql.sock. [...]]]></description>
			<content:encoded><![CDATA[<p>When installing PHP and MySQL on OSX  you may get the error <em>Can&#8217;t connect to local MySQL server through socket &#8216;/var/mysql/mysql.sock&#8217;</em>.   Or you may also get &#8220;<em>No such file or directory</em>&#8221; when calling mysql_connect from a PHP page.  This occurs because PHP is looking for the file mysql.sock in it&#8217;s typical installation location of /var/mysql/mysql.sock.  However the MySQL OSX installer actually puts the file in /tmp/mysql.sock.  There are two easy ways to solve the problem.</p>
<p><span id="more-266"></span></p>
<p><strong>Solution 1: Create a symbolic link</strong></p>
<p>Open terminal and do the following:</p>
<p>sudo su<br />
mkdir /var/mysql<br />
ln -s /tmp/mysql.sock /var/mysql/mysql.sock</p>
<p>You just created a symbolic link in the place where PHP expects the socket file to be located so it should be happy.</p>
<p><strong>Solution 2: Edit php.ini</strong></p>
<p>If you don&#8217;t like the idea of creating a symbolic link, you can also simply alter your php.ini file to point PHP to the real location of mysql.sock.</p>
<p>Locate /etc/php.ini.  (If php.ini doesn&#8217;t exist on your system, copy /etc/php.ini.default to /etc/php.ini).  You will likely have to do this from the terminal unless you have Finder configured to show hidden files.  Open the file and update the setting mysql.default_socket so it looks like this:</p>
<p>mysql.default_socket = /tmp/mysql.sock</p>
<p>To commit the change you need to restart Apache.  You can do that in System Settings -&gt; Sharing, then  uncheck, then recheck Web Sharing.</p>
]]></content:encoded>
			<wfw:commentRss>http://verysimple.com/2009/01/07/php-on-os-cant-connect-to-local-mysql-server-through-socket-varmysqlmysqlsock/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Working with dates in Flex AIR and SQLite</title>
		<link>http://verysimple.com/2008/09/09/working-with-dates-in-flex-air-and-sqlite/</link>
		<comments>http://verysimple.com/2008/09/09/working-with-dates-in-flex-air-and-sqlite/#comments</comments>
		<pubDate>Tue, 09 Sep 2008 21:38:49 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[AIR]]></category>
		<category><![CDATA[Apache]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[SQLite]]></category>

		<guid isPermaLink="false">http://www.verysimple.com/blog/?p=149</guid>
		<description><![CDATA[UPDATE 3/25/09: Paul Robertson from the AIR team stopped by and writes that declaring your SQLite column affinity (ie column type) as &#8220;DATE&#8221; will instruct AIR to handle all date conversions for you automatically.  The problems I experienced mainly surfaced in a DataGrid when using a DateField and I have not had a chance to [...]]]></description>
			<content:encoded><![CDATA[<p>UPDATE 3/25/09: Paul Robertson from the AIR team stopped by and writes that declaring your SQLite column affinity (ie column type) as &#8220;DATE&#8221; will instruct AIR to handle all date conversions for you automatically.  The problems I experienced mainly surfaced in a DataGrid when using a DateField and I have not had a chance to poke around with that yet.  Another approach is to extend DateField and override the &#8220;data&#8221; setter which is how the DataGrid supplies item editors with their value.  Then you can deal with casting issues manually, however that may be more of a hack.  The article below still has some good information that is still helpful for dealing with Dates in AIR/SQLite.</p>
<p>Working with SQLite and Flex/AIR Date values can be tricky and various caveats are not particularly well documented.  The confusion (for me) is that ActionScript is loaded with UTC functions, and SQLite will happily insert them into DATETIME columns.  Everything appears fine, however SQLite does not actually recognize this format as a Date and treats it as plain text.  You have no way to see this happened until you try to apply some date formatting functions and notice SQLite returning NULL.  SQLite is so lax about data integrity that you can insert anything into any column type and will never receive any warnings.  AIR, though, will attempt to cast values behind the scenes based on column types and so you will run into &#8216;Invalid Date&#8217; errors and weird glitches when attempting to update data.</p>
<p>The magic solution is the <a href="http://en.wikipedia.org/wiki/Julian_Day_Number">Julian Date Format</a> which both SQLite and AIR recognize as a date value.  This is somewhat surprising as ActionScript has no built-in support for outputting Julian dates.  If you&#8217;re like me, you may have already hacked up workarounds using int fields with timestamps, however your matching ActionScript class properties have to be hacked to match, and the hacking can trickle down throughout your code.  This also prevents you from using the SQLStatement.itemClass functionality, which is nice when using Cairngorm, DAOs, value objects, etc.</p>
<p><strong>To avoid the pain follow these rules when working with dates:</strong></p>
<p>1. If you want a strongly typed Date field in AIR, the relevant SQLite column must be defined as DATETIME.  The interesting thing about this is that DATETIME is not technically a <a href="http://www.sqlite.org/datatype3.html" target="_blank">recognized SQLite column type</a> and according to the SQLite docs it will be considered numeric.  But AIR is obviously looking at the column definition somewhere in the framework because it will refuse to automatically cast any value where the column type is not DATETIME.</p>
<p>2. Whenever inserting or updating DATETIME fields, you must store it in Julian format (or NULL).   SQLite will happily accept many common date formats.  However AIR will behave inconsistently.  Here is how to insert Julian dates in a variety of ways:</p>
<p><em>Inserting a Julian date manually via SQL:</em></p>
<p>To do this, simply have SQLite format your date value to Julian format using &#8216;%J&#8217;</p>
<pre>UPDATE my_table SET my_column = STRFTIME('%J','2008-01-02 03:04:05')</pre>
<p><em>Inserting a Julian date via AIR (with parameters):</em></p>
<p>Parameters are the best way to build SQL statements as you can use strongly typed Date variables and AIR will deal with the formatting for you.</p>
<pre>statement.text = "UPDATE my_table SET my_column = :my_value";
statement.parameters[":my_value"] = new Date(2008,0,2,3,4,5); // Jan 02, 2008 03:04:05</pre>
<p><em>Inserting a Julian date via AIR (without parameters):</em></p>
<p>If you are not using parameters, you have to pre-format the date into something that SQLite can parse.  This is surprisingly obnoxious and requires you to write a couple of helper functions. (Note &#8211; if you know of an easier way to do this, please post a comment.)</p>
<pre>public function lpad(original:Object, length:int, pad:String):String
{
var padded:String = original == null ? "" : original.toString();
while (padded.length &lt; length) padded = pad + padded;
return padded;
}

public function toSqlDate(dateVal:Date):String
{
return dateVal == null ? null : dateVal.fullYear
+ "-" + lpad(dateVal.month + 1,2,'0')  // month is zero-based
+ "-" + lpad(dateVal.date,2,'0')
+ " " + lpad(dateVal.hours,2,'0')
+ ":" + lpad(dateVal.minutes,2,'0')
+ ":" + lpad(dateVal.seconds,2,'0')
;
}

var myDate:Date = new Date(2008,0,2,3,4,5); // Jan 02, 2008 03:04:05
statement.text = "UPDATE my_table SET my_column = strftime('%J','" + toSqlDate(myDate) + "')";</pre>
<p><strong>Fudging data to work around AIRs validation</strong></p>
<p>If you absolutely refuse to change your schema (for example you insist on using timestamps, or you have to maintain compatibility with other clients) you can get AIR to play along during READ operations by altering your select statement like so:</p>
<pre>SELECT STRFTIME('%J',my_column) as my_column from my_table</pre>
<p>This does assume that the data is in a format that SQLite recognizes as a date.  If SQLite can&#8217;t parse the date value, then it will just return NULL.  For hilarity sake, you can also use <a href="http://www.verysimple.com/blog/2008/09/08/rediculous-date-formatting-in-sqlite/">this ridiculous date format </a>which surprisingly works with AIR.  A word of warning about this workaround is that, even though you will be able to read data, you may not be able to update data via SQLCommand parameters if your column types are DATETIME because AIR will complain about an invalid date (see errors below).  You will have either have to write your own SQL statements without parameters or else change your column types to int or varchar.</p>
<p><strong>Formatting a Julian date manually in SQL so you can read it:</strong></p>
<p>Julian values are great and all that, but it&#8217;s pretty much impossible to eyeball them when you&#8217;re working at the command line.  SQLite recognizes Julian formatting as a valid date, so you can use the STRFTIME function to format and output it any way you like.  Below is a simple example that is easier to read:</p>
<pre>SELECT STRFTIME('%Y-%m-%d %H:%M:%S',my_column) as my_column_formatted FROM my_table</pre>
<p><strong>Common errors that occur while working with dates:</strong></p>
<p><em>Invalid Date</em></p>
<p>You may see this in a DataGrid instead of the expected date value.  This is because you have a DATETIME column in SQLite, however the value is not in Julian format.  Even though SQLite may recognize it as a date value, AIR does not.  The solution is to clean your data so that all dates are Julian format, or alternatively change the column type to VARCHAR.</p>
<p><em>&#8216;Error #3115: SQL Error.&#8217;, details:&#8217;could not convert string value to date&#8217;</em></p>
<p>This error occurs when you try to update a record that has one or more DATETIME columns that do not have the date stored in Julian format.  The weird part is that even if you are not touching that specific column in your insert/update statement &#8211; AIR will still validate the Date and throw this error. The solution is to clean your data so that all dates are Julian format, or alternatively change the column type to VARCHAR.</p>
<p>If you have any tips or corrections please post a comment and I&#8217;ll incorporate it into the article.</p>
]]></content:encoded>
			<wfw:commentRss>http://verysimple.com/2008/09/09/working-with-dates-in-flex-air-and-sqlite/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Ridiculous date formatting in SQLite</title>
		<link>http://verysimple.com/2008/09/08/rediculous-date-formatting-in-sqlite/</link>
		<comments>http://verysimple.com/2008/09/08/rediculous-date-formatting-in-sqlite/#comments</comments>
		<pubDate>Mon, 08 Sep 2008 22:15:38 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[AIR]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[SQLite]]></category>

		<guid isPermaLink="false">http://www.verysimple.com/blog/?p=171</guid>
		<description><![CDATA[The following code outputs a SQLite date into a standard date format with month abbreviations that, believe it or not, Flex/AIR will accept as a Date value (Though SQLite itself doesn&#8217;t recognize it as a valid DATETIME!). I created this atrocious code while trying to figure out the mysterious interaction between AIR and SQLite date [...]]]></description>
			<content:encoded><![CDATA[<p>The following code outputs a SQLite date into a standard date format with month abbreviations that, believe it or not, Flex/AIR will accept as a Date value (Though SQLite itself doesn&#8217;t recognize it as a valid DATETIME!).  I created this atrocious code while trying to figure out the <a href="http://www.verysimple.com/blog/2008/09/09/working-with-dates-in-flex-air-and-sqlite/">mysterious interaction between AIR and SQLite date values</a>.  Julian time format is what you should use, though, for AIR applications.  I decided to post this code up just for curiosity sake and future reference:</p>
<pre>
SELECT
   CASE WHEN (  strftime('%m',my_column)   = '01') THEN ('Jan') ELSE '' END
|| CASE WHEN (  strftime('%m',my_column)   = '02') THEN ('Feb') ELSE '' END
|| CASE WHEN (  strftime('%m',my_column)   = '03') THEN ('Mar') ELSE '' END
|| CASE WHEN (  strftime('%m',my_column)   = '04') THEN ('Apr') ELSE '' END
|| CASE WHEN (  strftime('%m',my_column)   = '05') THEN ('May') ELSE '' END
|| CASE WHEN (  strftime('%m',my_column)   = '06') THEN ('Jun') ELSE '' END
|| CASE WHEN (  strftime('%m',my_column)   = '07') THEN ('Jul') ELSE '' END
|| CASE WHEN (  strftime('%m',my_column)   = '08') THEN ('Aug') ELSE '' END
|| CASE WHEN (  strftime('%m',my_column)   = '09') THEN ('Sep') ELSE '' END
|| CASE WHEN (  strftime('%m',my_column)   = '10') THEN ('Oct') ELSE '' END
|| CASE WHEN (  strftime('%m',my_column)   = '11') THEN ('Nov') ELSE '' END
|| CASE WHEN (  strftime('%m',my_column)   = '12') THEN ('Dec') ELSE '' END
|| STRFTIME(' %d %H:%M:%S GMT-0600 %Y', my_column)
FROM my_table
</pre>
]]></content:encoded>
			<wfw:commentRss>http://verysimple.com/2008/09/08/rediculous-date-formatting-in-sqlite/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Subtracting unsigned integers with MySQL</title>
		<link>http://verysimple.com/2007/12/07/subtracting-unsigned-integers-with-mysql/</link>
		<comments>http://verysimple.com/2007/12/07/subtracting-unsigned-integers-with-mysql/#comments</comments>
		<pubDate>Fri, 07 Dec 2007 05:01:57 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://www.verysimple.com/blog/2007/12/07/subtracting-unsigned-integers-with-mysql/</guid>
		<description><![CDATA[Unsigned integer values are used in a database when you only expect to contain positive values and no negative values (less than zero). If you know a certain field will never legitimately contain negative values, then this is actually the most efficient field type to select. There is a catch with unsigned ints however that [...]]]></description>
			<content:encoded><![CDATA[<p>Unsigned integer values are used in a database when you only expect to contain positive values and no negative values (less than zero).  If you know a certain field will never legitimately contain negative values, then this is actually the most efficient field type to select.</p>
<p>There is a catch with unsigned  ints however that can create problems for you if you&#8217;re not careful.  That is, when you subtract unsigned ints, you will <em>always </em>get a positive value back no matter what.  What does that mean?</p>
<p>Say you have a table for products with two unsigned fields: <strong>qty_in_stock</strong> and <strong>qty_sold</strong>.  Lets assume for whatever reason you oversold your inventory and qty_in_stock now equals  100, but qty_sold = 101.  So take the following statement:</p>
<pre>SELECT qty_in_stock - qty_sold as qty_remaining FROM products</pre>
<p>You would expect qty_remaining to be -1, right?  Wrong!  In fact MySQL returns <strong>18446744073709551615</strong> !</p>
<p>Why would this happen?  Well, because MySQL is built so that when you perform a math operation on two unsigned ints, it will always return an unsigned int.  And -1 is technically an out-of-bounds value for an unsigned field type.  Instead of complaining, MySQL returns the value that would have represented -1 if it were unsigned which is 18446744073709551615.</p>
<p>Mathematically, I suppose this is correct, however it doesn&#8217;t make any logical sense to me.  If anything, I think MySQL should throw an out-of-bounds error when this happens because the default behavior seems very unintuitive to me.  It is as though they are trying to say that one positive value subtracted from another can never result in a negative value.  Of course this is false, but that is how MySQL works.</p>
<p>There are two solutions to this.  The first is to simply use signed ints if you ever expect them to be used in a subtraction formula.  You waste some space, but it&#8217;s an easy fix.</p>
<p>The second solution is, if you are able to edit your SQL statement that have the subtraction, you can use the MySQL cast function.  The example from above could be converted to the following:</p>
<pre>SELECT cast(qty_in_stock - qty_sold as signed) as qty_remaining FROM products</pre>
<p>So there is a solution to this &#8220;problem&#8221; if you will.  You can read more about this subject on the MySQL site at <a href="http://dev.mysql.com/doc/refman/4.1/en/cast-functions.html" target="_blank">http://dev.mysql.com/doc/refman/4.1/en/cast-functions.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://verysimple.com/2007/12/07/subtracting-unsigned-integers-with-mysql/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Beyond auto-id: Advanced Sequential Numbering with MySQL</title>
		<link>http://verysimple.com/2007/06/09/insert-sequential-numbers-in-mysql/</link>
		<comments>http://verysimple.com/2007/06/09/insert-sequential-numbers-in-mysql/#comments</comments>
		<pubDate>Sun, 10 Jun 2007 02:16:55 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://www.verysimple.com/blog/2007/06/09/insert-sequential-numbers-in-mysql/</guid>
		<description><![CDATA[MySQL auto-id function provides the ability to automatically create a new id for each new record on insert. This works great for unique ids, but sometimes more logic is required. For a recent assignment we needed to populate a table that reflects seating in a stadium. The seating was typical of most venues consisting of [...]]]></description>
			<content:encoded><![CDATA[<p>MySQL auto-id function provides the ability to automatically create a new id for each new record on insert.  This works great for unique ids, but sometimes more logic is required.</p>
<p>For a recent assignment we needed to populate a table that reflects seating in a stadium.  The seating was typical of most venues consisting of Aisles and Seats.  For example, A-1, A-2, A-3, B-1, B-2, B-3, and so on. When the table was initially populated, the seat_number field was all set at it&#8217;s default value of &#8217;1&#8242;.  So we needed sequential numbers for the seats, but the count had to start over with each new Aisle.  This could have been done easily in a scripting language, but what fun is that!  We wanted to accomplish the numbering in one regular SQL statement.</p>
<p>This problem would be easily solved using Oracle&#8217;s rownum functionwhere we can get a sequential id for each row within a resultset.  But, alas, MySQL doesn&#8217;t have a rownum function.  What we did find, however, is a wonderful hack on <a href="http://markmal.blogspot.com/2006/04/oracle-like-rownum-in-mysql.html" target="_blank">Mark Malakonov&#8217;s blog</a> that duplicates this functionality for MySQL.</p>
<p>The final query, which only updates Aisle &#8216;A&#8217; is here:</p>
<pre>update venue_seat set seat_number =
(select @rownum:=@rownum+1 rownum FROM (SELECT @rownum:=0) r)
where aisle = 'A'
</pre>
<p>These fields obviously relate to a specific schema, however the @rownum trick can be used to generate sequential numbers for your tables as well. If you need to update or populate a table with sequential numbers but need some additional logic, this is a handy trick to have in your toolbox.</p>
]]></content:encoded>
			<wfw:commentRss>http://verysimple.com/2007/06/09/insert-sequential-numbers-in-mysql/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>MySQL Error Number 1005 Can&#8217;t create table &#8216;.\mydb\#sql-328_45.frm&#8217; (errno: 150)</title>
		<link>http://verysimple.com/2006/10/22/mysql-error-number-1005-cant-create-table-mydbsql-328_45frm-errno-150/</link>
		<comments>http://verysimple.com/2006/10/22/mysql-error-number-1005-cant-create-table-mydbsql-328_45frm-errno-150/#comments</comments>
		<pubDate>Mon, 23 Oct 2006 04:06:36 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.verysimple.com/blog/?p=58</guid>
		<description><![CDATA[MySQL Error Number 1005 Can&#8217;t create table &#8216;.\mydb\#sql-328_45.frm&#8217; (errno: 150) If you get this error while trying to create a foreign key, it can be pretty frustrating. The error about not being able to create a .frm file seems like it would be some kind of OS file permission error or something but this is [...]]]></description>
			<content:encoded><![CDATA[<p>MySQL Error Number 1005<br />
Can&#8217;t create table &#8216;.\mydb\#sql-328_45.frm&#8217; (errno: 150)</p>
<p>If you get this error while trying to create a foreign key, it can be pretty frustrating. The error about not being able to create a .frm file seems like it would be some kind of OS file permission error or something but this is not the case. This error has been reported as a bug on the MySQL developer list for ages, but it is actually just a misleading error message.</p>
<p>In every case this is due to something about the relationship that MySQL doesn&#8217;t like. Unfortunately it doesn&#8217;t specify what the exact issue is.</p>
<p><strong>First Steps:</strong></p>
<p><em>If you have admin permission on the server, you may want to start by running the MySQL command &#8220;SHOW INNODB STATUS&#8221; (or MySQL 5.5 &#8220;SHOW ENGINE INNODB STATUS&#8221;) immediately after receiving the error. This command displays log info and error details. (Thanks Jonathan for the tip)</em></p>
<p><em>If your script runs fine on one server, but gives an error when you try to run it on a different server, then there is a good chance that #6 is the problem.  Different versions of MySQL have different default charset setting and you may have unknowingly assigned different charsets on the different servers.<br />
</em></p>
<p><strong>Known Causes:</strong></p>
<p>Below is a running list of known causes that people have reported for the dreaded errno 150:<strong><br />
</strong></p>
<ol>
<li>The two key fields type and/or size is not an exact match. For example, if one is INT(10) the key field needs to be INT(10) as well and not INT(11) or TINYINT. You may want to confirm the field size using SHOW CREATE TABLE because Query Browser will sometimes visually show just INTEGER for both INT(10) and INT(11). You should also check that one is not SIGNED and the other is UNSIGNED. They both need to be exactly the same. (<a href="http://www.verysimple.com/blog/?p=57">More about signed vs unsigned here</a>).</li>
<li>One of the key field that you are trying to reference does not have an index and/or is not a primary key. If one of the fields in the relationship is not a primary key, you must create an index for that field. (thanks to Venkatesh and Erichero and Terminally Incoherent for this tip)</li>
<li>The foreign key name is a duplicate of an already existing key. Check that the name of your foreign key is unique within your database. Just add a few random characters to the end of your key name to test for this. (Thanks to Niels for this tip)</li>
<li>One or both of your tables is a MyISAM table. In order to use foreign keys, the tables must both be InnoDB. (Actually, if both tables are MyISAM then you won&#8217;t get an error message &#8211; it just won&#8217;t create the key.) In Query Browser, you can specify the table type.</li>
<li>You have specified a cascade ON DELETE SET NULL, but the relevant key field is set to NOT NULL.  You can fix this by either changing your cascade or setting the field to allow NULL values. (Thanks to Sammy and J Jammin)</li>
<li>Make sure that the Charset and Collate options are the same both at the table level as well as individual field level for the key columns. (Thanks to FRR for this tip)</li>
<li>You have a default value (ie default=0) on your foreign key column (Thanks to Omar for the tip)</li>
<li>One of the fields in the relationship is part of a combination (composite) key and does not have it&#8217;s own individual index. Even though the field has an index as part of the composite key, you must create a separate index for only that key field in order to use it in a constraint. (Thanks to Alex for this tip)</li>
<li>You have a syntax error in your ALTER statement or you have mistyped one of the field names in the relationship (Thanks to Christian &amp; Mateo for the tip)</li>
<li>The name of your foreign key exceeds the max length of 64 chars.  (Thanks to Nyleta for the tip)</li>
</ol>
<p>The MySQL documentation includes a <a href="http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html" target="_blank">page explaining requirements for foreign keys</a>. Though they don&#8217;t specifically indicate it, these are all potential causes of errno 150. If you still haven&#8217;t solved your problem you may want to check there for deeper technical explainations.</p>
<p>If you run into this error and find that it&#8217;s caused by something else, please leave a comment and I&#8217;ll add it to the list.</p>
]]></content:encoded>
			<wfw:commentRss>http://verysimple.com/2006/10/22/mysql-error-number-1005-cant-create-table-mydbsql-328_45frm-errno-150/feed/</wfw:commentRss>
		<slash:comments>194</slash:comments>
		</item>
	</channel>
</rss>

