<?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>code.openark.org &#187; python</title>
	<atom:link href="http://code.openark.org/blog/tag/python/feed" rel="self" type="application/rss+xml" />
	<link>http://code.openark.org/blog</link>
	<description>Blog by Shlomi Noach</description>
	<lastBuildDate>Wed, 01 Feb 2012 08:19:12 +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>oak-hook-general-log: your poor man&#039;s Query Analyzer</title>
		<link>http://code.openark.org/blog/mysql/oak-hook-general-log-your-poor-mans-query-analyzer</link>
		<comments>http://code.openark.org/blog/mysql/oak-hook-general-log-your-poor-mans-query-analyzer#comments</comments>
		<pubDate>Wed, 15 Dec 2010 17:46:06 +0000</pubDate>
		<dc:creator>shlomi</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Analysis]]></category>
		<category><![CDATA[logs]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[openark kit]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[scripts]]></category>

		<guid isPermaLink="false">http://code.openark.org/blog/?p=3032</guid>
		<description><![CDATA[The latest release of openark kit introduces oak-hook-general-log, a handy tool which allows for some analysis of executing queries. Initially I just intended for the tool to be able to dump the general log to standard output, from any machine capable to connect to MySQL. Quick enough, I realized the power it brings. With this [...]]]></description>
			<content:encoded><![CDATA[<p>The latest release of <a href="http://code.openark.org/forge/openark-kit">openark kit</a> introduces <a href="http://openarkkit.googlecode.com/svn/trunk/openarkkit/doc/html/oak-hook-general-log.html">oak-hook-general-log</a>, a handy tool which allows for some analysis of executing queries.</p>
<p>Initially I just intended for the tool to be able to dump the general log to standard output, from any machine capable to connect to MySQL. Quick enough, I realized the power it brings.</p>
<p>With this tool, one can dump to standard output all queries using temporary tables; or using a specific index; or doing a full index scan; or just follow up on connections; or... For example, the following execution will only log queries which make for filesort:</p>
<blockquote>
<pre>oak-hook-general-log --user=root --host=localhost --password=123456 --filter-explain-filesort</pre>
</blockquote>
<h4>The problem with using the standard logs</h4>
<p>So you have the <em>general log</em>, which you don't often enable, since it tends to grow huge within moments. You then have the <em>slow log</em>. Slow log is great, and is among the top tools for MySQL diagnosis.</p>
<p>The slow log allows for <strong>log-queries-not-using-indexes</strong>, which is yet another nice feature. Not only should you log any query running for over <strong>X</strong> seconds, but also log any query which does not use an index.</p>
<p>Wait. This logs all single-row tables (no single row table will use an index), as well as very small tables (a common <strong>20</strong> rows lookup table will most often be scanned). These are OK scans. This makes for some noise in the slow log.</p>
<p>And how about queries which do use an index, but do so poorly? They use an index, but retrieve some <strong>12,500,000</strong> rows, <em>using temporary</em> table &amp; <em>filesort</em>?</p>
<h4>What oak-hook-general-log does for you</h4>
<p>This tool streams out the general log, and filters out queries based on their <em>role</em> or on their <em>execution plan</em>.</p>
<p>To work at all, it must enable the general log. Moreover, it directs the general log to log table. Mind that this makes for a performance impact, which is why the tool auto-terminates and restores original log settings (default is <strong>1</strong> minute, configurable). It's really not a tool you should keep running for days. But during the few moments it runs, it will:</p>
<ul>
<li>Routinely rotate the <strong>mysql.general_log</strong> table so that it doesn't fill up</li>
<li>Examine entries found in the general log</li>
<li>Cross reference entries to the PROCESSLIST so as to deduce database context (<a href="http://bugs.mysql.com/bug.php?id=52554">bug #52554</a>)</li>
<li>If required and appropriate, evaluate a query's execution plan</li>
<li>Decide whether to dump each entry based on filtering rules</li>
</ul>
<h4>Filtering rules</h4>
<p>Filtering rules are passed as command line options. At current, only one filtering rule applies (if more than one specified only one is used, so no point in passing more than one). Some of the rules are:<span id="more-3032"></span></p>
<ul>
<li><strong>filter-connection</strong>: only log connect/quit entries</li>
<li><strong>filter-explain-fullscan</strong>: only log full table scans</li>
<li><strong>filter-explain-temporary</strong>: only log queries which create implicit temporary tables</li>
<li><strong>filter-explain-rows-exceed</strong>: only log queries where more than <strong>X</strong> number of rows are being accessed on some table (estimated)</li>
<li><strong>filter-explain-total-rows-exceed</strong>: only log queries where more than <strong>X</strong> number of rows are accessed on all tables combined (estimated, with possibly incorrect numbers on some queries)</li>
<li><strong>filter-explain-key</strong>: only log queries using a specific index. This feature somewhat overlaps with Maatkit's <em>mk-index-usage</em> (read <a href="http://www.mysqlperformanceblog.com/2010/11/11/advanced-index-analysis-with-mk-index-usage/">announcement</a>).</li>
<li><strong>filter-explain-contains</strong>: a general purpose <em>grep</em> on the execution plan. Log queries where the execution plan contains <em>some text</em>.</li>
</ul>
<p>There are other filters, and I will possibly add more in due time.</p>
<p>Here are a couple cases I used <em>oak-hook-general-log</em> for:</p>
<h4>Use case: temporary tables</h4>
<p>I have a server with this alarming chart (courtesy <a href="http://code.openark.org/forge/mycheckpoint">mycheckpoint</a>) of temporary tables:</p>
<blockquote>
<pre><img class="alignnone" title="Created tmp tables per second" src="http://chart.apis.google.com/chart?cht=lc&amp;chs=370x180&amp;chts=303030,12&amp;chtt=Latest+24+hours:+Dec+9,+06:30++-++Dec+10,+06:30&amp;chf=c,s,ffffff&amp;chdl=created_tmp_tables_psec|created_tmp_disk_tables_psec&amp;chdlp=b&amp;chco=ff8c00,4682b4&amp;chd=s:yzzy02zzz100zzz0rv9zz0zyzyz0yy2xz1t11xzztz0xr1xt2tz07vwzz100100z31z111yz1vzzzzz1zs80r902s1111010y20z03z11487zz011z11011002w0q5rxxz0y00z0s02xy1yy0,gggfghggfgggghhgYekhhghhhhhghfjghhdihfhgdghgZhgcicihpcehhhhhhhifkigjihghjehgiigjgYqiYqgiaihiifkhekhfijgiihhggggggggggfhgghffZoYgggggggggdihfggghg&amp;chxt=x,y&amp;chxr=1,0,35.060000&amp;chxl=0:||08:00||+||12:00||+||16:00||+||20:00||+||00:00||+||04:00||+|&amp;chxs=0,505050,10,0,lt&amp;chg=4.17,25,1,2,2.08,0&amp;chxp=0,2.08,6.25,10.42,14.59,18.76,22.93,27.10,31.27,35.44,39.61,43.78,47.95,52.12,56.29,60.46,64.63,68.80,72.97,77.14,81.31,85.48,89.65,93.82,97.99&amp;tsstart=2010-12-09+06:30:00&amp;tsstep=600" alt="" width="370" height="180" />
</pre>
</blockquote>
<p>What could possibly create <strong>30</strong> temporary tables per second on average?</p>
<p>The slow log produced nothing helpful, even with <strong>log-queries-not-using-indexes</strong> enabled. There were a lot of queries not using indexes there, but nothing at these numbers. With:</p>
<blockquote>
<pre>oak-hook-general-log --filter-explain-temporary</pre>
</blockquote>
<p>enabled for <strong>1</strong> minute, nothing came out. Weird. Enabled for <strong>5</strong> minutes, I got one entry. Turned out a scheduled script, acting once per <strong>5</strong> minutes, was making a single complicated query involving many nested views, which accounted for some <em>hundreds</em> of temporary tables created. All of them very small, query time was very fast. There is no temporary tables problem with this server, case closed.</p>
<h4>Use case: connections</h4>
<p>A server had issues with some exceptions being thrown on the client side. There was a large number of new connections created per second although the client was using a connection pool. Suspecting the pool didn't work well, I issued:</p>
<blockquote>
<pre>oak-hook-general-log --filter-connect</pre>
</blockquote>
<p>The pool was working well, all right. No entries for that client were recorder in <strong>1</strong> minute of testing. However, it turned out some old script was flooding the MySQL server with requests, every second. The log showed root@somehost, and sure enough, the script was disabled. Exceptions were due to another reason; it was good to eliminate a suspect.</p>
<p>Some of the tool's use case is relatively easy to solve with tail, grep &amp; awk; others are not. I am using it more and more often, and find it to make significant shortcuts in tracking down queries.</p>
<h4>Get it</h4>
<p>Download the tool as part of <em>openark kit</em>: access the <a href="http://code.google.com/p/openarkkit/">openark kit project page</a>.</p>
<p>Or get the <a href="http://openarkkit.googlecode.com/svn/trunk/openarkkit/src/oak/oak-hook-general-log.py">source code</a> directly.</p>
<p>Feedback is most welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.openark.org/blog/mysql/oak-hook-general-log-your-poor-mans-query-analyzer/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>openark-kit (rev. 170): new tools, new functionality</title>
		<link>http://code.openark.org/blog/mysql/openark-kit-rev-170-new-tools-new-functionality</link>
		<comments>http://code.openark.org/blog/mysql/openark-kit-rev-170-new-tools-new-functionality#comments</comments>
		<pubDate>Wed, 15 Dec 2010 06:31:24 +0000</pubDate>
		<dc:creator>shlomi</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Analysis]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[openark kit]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[Replication]]></category>
		<category><![CDATA[scripts]]></category>

		<guid isPermaLink="false">http://code.openark.org/blog/?p=3124</guid>
		<description><![CDATA[I'm pleased to announce a new release of the openark kit. There's a lot of new functionality inside; following is a brief overview. The openark kit is a set of utilities for MySQL. They solve everyday maintenance tasks, which may be complicated or time consuming to work by hand. It's been a while since the [...]]]></description>
			<content:encoded><![CDATA[<p>I'm pleased to announce a new release of the <a href="http://code.openark.org/forge/openark-kit">openark kit</a>. There's a lot of new functionality inside; following is a brief overview.</p>
<p>The <em>openark kit</em> is a set of utilities for MySQL. They  solve everyday maintenance tasks, which may be complicated or time  consuming to work by hand.</p>
<p>It's been a while since the last announced release. Most of my attention was on <a href="http://code.openark.org/forge/mycheckpoint">mycheckpoint</a>, building new features, writing documentation etc. However my own use of <em>openark kit</em> has only increased in the past few months, and there's new useful solutions to common problems that have been developed.</p>
<p>I've used and improved many tools over this time, but doing the final cut, along with proper documentation, took some time. Anyway, here are the highlights:</p>
<h4>New tool: oak-hook-general-log</h4>
<p><em>oak-hook-general-log</em> hooks up a MySQL server and dumps the general log based on filtering rules, applying to query role or execution plan. It is possible to only dump connect/disconnect entries, queries which make a full table scan, or use temporary tables, or scan more than X number of rows, or...</p>
<p>I'll write more on this tool shortly.</p>
<h4>New tool: oak-prepare-shutdown</h4>
<p>This tool makes for an orderly and faster shutdown by safely stopping replication, and flushing InnoDB pages to disk prior to shutting down (keeping server available for connections even while attempting to flush dirty pages to disk). A typical use case would be:</p>
<blockquote>
<pre>oak-prepare-shutdown --user=root --ask-pass --socket=/tmp/mysql.sock &amp;&amp; /etc/init.d/mysql stop</pre>
</blockquote>
<h4>New tool: oak-repeat query</h4>
<p><em>oak-repeat-query</em> repeats executing a given query until some condition holds. The condition can be:</p>
<ul>
<li>Number of given iterations has been reached</li>
<li>Given time has elapsed</li>
<li>No rows have been affected by query</li>
</ul>
<p>The tool comes in handy for cleanup jobs, warming up caches, etc.<span id="more-3124"></span></p>
<h4>New tool: oak-get-slave-lag</h4>
<p>This simple tool just returns the number of seconds a slave is behind master. But it also returns with an appropriate exit code, based on a given threshold: <strong>0</strong> when lag is good, <strong>1</strong> (error exit code) when lag is too great or slave fails to replicate.</p>
<p>This tool has been used by 3rd party applications, such as a load balancer, to determine whether a slave should be accessed.</p>
<h4>Updated tool: oak-chunk-update</h4>
<p>This extremely useful utility breaks down very long queries into smaller chunks. These could be queries which should affect a huge amount of rows, or queries which cannot utilize an index.</p>
<p>Updates to the tool include limiting the range of rows the tool scans, by specifying start and stop position (either by providing constant values or by SELECT query). Also added is auto-termination when no rows are found to be affected. Last, it is possible to override INFORMATION_SCHEMA lookup by explicitly specifying chunking key.</p>
<p>This tool works great for your daily/weekly/monthly batch jobs; in creating DWH tables; populating new columns; purging old entries; clearing data based on non-indexed values; generating summary tables; and more.</p>
<h4>Frozen tool: oak-apply-ri</h4>
<p>I haven't been using this tool for a while. The main work down by this tool can be done with <em>oak-chunk-update</em>. There are some additional safety checks <em>oak-apply-ri</em> provides; I'm thinking over if they justify the tool's existence.</p>
<h4>Frozen tool: oak-online-alter-table</h4>
<p>With the appearance of Facebook’s <a href="http://www.facebook.com/note.php?note_id=430801045932">Online Schema Change</a> (OSC) tool, which derives from <em>oak-online-alter-table</em>, I'm not sure I will continue developing the tool. I intend to wait for general feedback on OSC before making a decision.</p>
<h4>Documentation</h4>
<p><a href="http://openarkkit.googlecode.com/svn/trunk/openarkkit/doc/html/introduction.html">Documentation</a> is now part of <em>openark kit</em>'s SVN repository.</p>
<h4>Download</h4>
<p>The <em>openark kit</em> project is currently hosted by Google Code.  Downloads are available at the Google Code <a href="http://code.google.com/p/openarkkit/">openark kit project page</a>.</p>
<p>Downloads are available in the following packaging formats:</p>
<ul>
<li><strong>.deb</strong> package, to be installed on <em>debian</em>, <em>ubuntu</em> and otherwise debian based distributions.</li>
<li><strong>.rpm</strong> package, architecture free (<em>noarch</em>), for RPM supporting Linux distributions such as <em>RedHat</em>, <em>Fedora</em>, <em>CentOS</em> etc.</li>
<li><strong>.tar.gz</strong> using python's distutils installer.</li>
<li><strong>source</strong>, directly retrieved from SVN or from above python package.</li>
<li>Some distribution specific <a href="http://software.opensuse.org/search?baseproject=ALL&amp;p=1&amp;q=openark-kit">RPM packages</a>, courtesy Lenz Grimmer.</li>
</ul>
<h4>Feedback</h4>
<p>Your feedback is welcome! I may not always respond promptly; and I confess that some bugs were left open for more than I would have liked them to. I hope to make for good quality of code, and bug reporting is one major factor you can control.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.openark.org/blog/mysql/openark-kit-rev-170-new-tools-new-functionality/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>mycheckpoint (rev 208): aggregation tables, enhanced charting, RPM distribution</title>
		<link>http://code.openark.org/blog/mysql/mycheckpoint-rev-208-aggregation-tables-enhanced-charting-rpm-distribution</link>
		<comments>http://code.openark.org/blog/mysql/mycheckpoint-rev-208-aggregation-tables-enhanced-charting-rpm-distribution#comments</comments>
		<pubDate>Mon, 08 Nov 2010 10:45:45 +0000</pubDate>
		<dc:creator>shlomi</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Monitoring]]></category>
		<category><![CDATA[mycheckpoint]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[scripts]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://code.openark.org/blog/?p=3066</guid>
		<description><![CDATA[Revision 208 of mycheckpoint, a MySQL monitoring solution, has been released. New and updated in this revision: Aggregation tables: aggregated data makes for fast reports on previously slow queries. Enhanced charting: interactive charts now present time stamps dynamically (see demo); "Zoom in" charts are available (see demo) on mycheckpoint's HTTP server. RPM distribution: a "noarch" [...]]]></description>
			<content:encoded><![CDATA[<p>Revision <strong>208</strong> of <a href="../../forge/mycheckpoint">mycheckpoint</a>, a MySQL monitoring solution, has  been released. New and updated in this revision:</p>
<ul>
<li><strong>Aggregation tables</strong>: aggregated data makes for fast reports on previously slow queries.</li>
<li><strong>Enhanced charting</strong>: interactive charts now present time stamps dynamically (see <a href="http://mycheckpoint.googlecode.com/svn/trunk/doc/html/sample/http/mcp_sql00/sv_report_html_brief"><strong>demo</strong></a>); "Zoom in" charts are available (see <a href="http://mycheckpoint.googlecode.com/svn/trunk/doc/html/sample/http/mcp_sql00/zoom/questions"><strong>demo</strong></a>) on <em>mycheckpoint</em>'s HTTP server.</li>
<li><strong>RPM distribution</strong>: a "noarch" RPM <em>mycheckpoint</em> build is now available.</li>
<li>Initial work on formalizing test environment</li>
</ul>
<p><em>mycheckpoint</em> celebrates one year of existence!</p>
<h4>Aggregation tables</h4>
<p>I really wanted to avoid using these: everything was so more beautiful with one single dataset and dozens of supporting views (OK, the views themselves are hardly "beautiful").</p>
<p>However it was impossible (for my level of expertise) to optimize query performance what with all those views on per-hour and per-day aggregation. The GROUP BYs and the JOINs did not make it possible for condition pushdown (i.e. using MERGE algorithm) where desired.</p>
<p>As result, mycheckpoint now manages aggregation tables: per-hour and per-day. The impact on sample taking is neglect able (making for two additional fast queries), but the impact on reading aggregated data is overwhelming. Generating a HTML full report could take a few minutes to complete. It now returns in no time. This makes charting more attractive, and allows for enhanced charting, such as zooming in on charts, as described following.</p>
<p>Aggregation tables will automatically be created and retroactively populated upon using revision 208. There's nothing special to do; be advised that for one single execution of <em>mycheckpoint</em>, many INSERT queries are going to be executed. Shouldn't take more than a couple minutes on commodity hardware and a few months of history.</p>
<p>It is possible to disable aggregation tables, or make for a complete rebuild of tables; by default, though, aggregation is ON.</p>
<h4>Enhanced charting</h4>
<p>Two enhancements here:<span id="more-3066"></span></p>
<ol>
<li>The interactive line charts already know how to update legend data as mouse hovers over them. Now they also present accurate date &amp; time. This provides with fully informative charts.</li>
<li>As with other monitoring tools, it is possible to "zoom in" on a chart: zooming in will present any chart in "last 24 hours", "last 10 days" and "complete history" views, magnified on screen. See <a href="http://mycheckpoint.googlecode.com/svn/trunk/doc/html/sample/http/mcp_sql00/zoom/questions"><strong>demo</strong></a> here.</li>
</ol>
<h4>RPM distribution</h4>
<p>No excuse for this being so late, I know. But RPM distribution is now <a href="http://code.google.com/p/mycheckpoint/">available</a>. Yeepee!</p>
<p>This is a <em>noarch</em> distribution, courtesy of Python's <a href="http://docs.python.org/distutils/">distutils</a>; you should be able to install the package on any RPM supporting platform. I have only tested in on CentOS; feedback is welcome.</p>
<h4>Future plans</h4>
<p>Work is going on. These are the non-scheduled future tasks I see:</p>
<ul>
<li>Monitoring InnoDB Plugin &amp; XtraDB status.</li>
<li>A proper <em>man</em> page.</li>
<li>Anything else that interests me &amp; the users.</li>
</ul>
<h4>Try it out</h4>
<p>Try out <em>mycheckpoint</em>. It’s a different kind of monitoring    solution. Simple monitoring (charting) is immediate. For more  interesting results you will need basic SQL skills, and in return you’ll  get a lot   of power under your hands.</p>
<ul>
<li>Download mycheckpoint <a href="https://code.google.com/p/mycheckpoint/">here</a></li>
<li>Visit the project’s <a href="../../forge/mycheckpoint">homepage</a></li>
<li>Browse the <a href="../../forge/mycheckpoint/documentation">documentation</a></li>
<li>Report <a href="https://code.google.com/p/mycheckpoint/issues/list">bugs</a></li>
</ul>
<p><em>mycheckpoint</em> is released under the <a href="http://www.opensource.org/licenses/bsd-license.php">New BSD  License</a>.</p>
<p>Umm, I'll repeat this last one: <em>mycheckpoint</em> is released under the <a href="http://www.opensource.org/licenses/bsd-license.php">New BSD  License</a>. Still, and will continue to be. Thanks for the <a href="http://code.openark.org/blog/mysql/openark-kit-facebook-online-schema-change-and-thoughts-on-open-source-licenses#comments">good advice</a> by Lenz, Domas and others.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.openark.org/blog/mysql/mycheckpoint-rev-208-aggregation-tables-enhanced-charting-rpm-distribution/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Thoughts and ideas for Online Schema Change</title>
		<link>http://code.openark.org/blog/mysql/thoughts-and-ideas-for-online-schema-change</link>
		<comments>http://code.openark.org/blog/mysql/thoughts-and-ideas-for-online-schema-change#comments</comments>
		<pubDate>Thu, 07 Oct 2010 08:29:10 +0000</pubDate>
		<dc:creator>shlomi</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Indexing]]></category>
		<category><![CDATA[INFORMATION_SCHEMA]]></category>
		<category><![CDATA[InnoDB]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[openark kit]]></category>
		<category><![CDATA[Opinions]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[Schema]]></category>
		<category><![CDATA[scripts]]></category>
		<category><![CDATA[Triggers]]></category>

		<guid isPermaLink="false">http://code.openark.org/blog/?p=3005</guid>
		<description><![CDATA[Here's a few thoughts on current status and further possibilities for Facebook's Online Schema Change (OSC) tool. I've had these thoughts for months now, pondering over improving oak-online-alter-table but haven't got around to implement them nor even write them down. Better late than never. The tool has some limitations. Some cannot be lifted, some could. [...]]]></description>
			<content:encoded><![CDATA[<p>Here's a few thoughts on current status and further possibilities for Facebook's <a href="http://www.facebook.com/note.php?note_id=430801045932">Online Schema Change</a> (OSC) tool. I've had these thoughts for months now, pondering over improving <a href="../../forge/openark-kit/oak-online-alter-table">oak-online-alter-table</a> but haven't got around to implement them nor even write them down. Better late than never.</p>
<p>The tool has some limitations. Some cannot be lifted, some could. Quoting from the <a href="http://www.facebook.com/notes/mysql-at-facebook/online-schema-change-for-mysql/430801045932">announcement</a> and looking at the code, I add a few comments. I conclude with a general opinion on the tool's abilities.</p>
<h4>"The original table must have PK. Otherwise an error is returned."</h4>
<p>This restriction could be lifted: it's enough that the table has a UNIQUE KEY. My original <em>oak-online-alter-table</em> handled that particular case. As far as I see from their code, the Facebook code would work just as well with any unique key.</p>
<p>However, this restriction is of no real interest. As we're mostly interested in InnoDB tables, and since any InnoDB table <em>should have</em> a PRIMARY KEY, we shouldn't care too much.</p>
<h4>"No foreign keys should exist. Otherwise an error is returned."</h4>
<p>Tricky stuff. With <em>oak-online-alter-table</em>, changes to the original table were immediately reflected in the <em>ghost</em> table. With InnoDB tables, that meant same transaction. And although I never got to update the text and code, there shouldn't be a reason for not using child-side foreign keys (the child-side is the table on which the FK constraint is defined).</p>
<p>The Facebook patch works differently: it captures changes and writes them to a <strong>delta</strong> table,  to be later (asynchronously) analyzed and make for a <em>replay</em> of actions on the <em>ghost</em> table.<span id="more-3005"></span></p>
<p>So in the Facebook code, some cases will lead to undesired behavior. Consider two tables, <strong>country</strong> and <strong>city</strong>, with city holding a RESTRICT/NO ACTION foreign key on <strong>country</strong>'s id. Now consider the scenario:</p>
<ol>
<li>Rows from <strong>city</strong> are DELETEd, where the country Id is Spain's.
<ul>
<li><strong>city</strong>'s ghost table is still unaffected, Spain's cities are still there.</li>
<li>A change is written to the delta table to mark these rows for deletion.</li>
</ul>
</li>
<li>A DELETE is issued on <strong>country</strong>'s Spain record.
<ul>
<li>The DELETE should work, from the user's perspective</li>
<li>But it will fail: city's ghost table has not received the changes yet. There's still matching rows. The NO ACTION constraint will fail the DELETE statement.</li>
</ul>
</li>
</ol>
<p>Now, this does not lead to corruption, just to seemingly unreasonable behavior on the database part. This behavior is probably undesired. NO ACTION constraint won't do.</p>
<p>However, with CASCADE or SET NULL options, there is less of an issue: operations on the parent table (e.g. <strong>country</strong>) cannot fail. We must make sure operations on the ghost table make it consistent with the original table (e.g. <strong>city</strong>).</p>
<p>Consider the following scenario:</p>
<ol>
<li>A new country is created, called "Sleepyland". An INSERT is made to <strong>country</strong>.
<ul>
<li>Both <strong>city</strong> and <strong>city</strong>'s ghost are immediately aware of it.</li>
</ul>
</li>
<li>A new town is created and INSERTed to <strong>city</strong>. The town is called "Naphaven".
<ul>
<li>The change takes time to propagate to <strong>city</strong>'s ghost table.</li>
</ul>
</li>
<li>Meanwhile, we realized we made a mistake. We've been had. There's no such city nor country.
<ol>
<li>We DELETE "Naphaven" from <strong>city</strong>.</li>
<li>We DELETE "Sleepyland" from <strong>country</strong>.</li>
</ol>
<ul>
<li>Note that <strong>city</strong>'s ghost table still hasn't caught up with the changes.</li>
</ul>
</li>
<li>Eventually, the INSERT statement for "Naphaven" reaches <strong>city</strong>'s ghost table.
<ul>
<li>What should happen now? The INSERT cannot succeed.</li>
<li>Will this fail the entire process?</li>
</ul>
</li>
</ol>
<p>Looking at the PHP code, I see that changes written on the <strong>delta</strong> table are blindly replayed on the ghost table.</p>
<p>Since the process is asynchronous, this should not be the case. We can solve the above if we use INSERT IGNORE instead of INSERT. The statement will fail without failing anything else. The row cannot exist, and that's because the original row does not exist anymore.</p>
<p>Unlike a replication corruption, this does not lead to accumulation mistakes. The <strong>replay</strong> is static, somewhat like in <em>binary log format</em>. Changes are <em>just written</em>, regardless of existing data.</p>
<p>I have given this considerable thought, and I can't say I've covered all the possible scenario. However I believe that with proper use of INSERT IGNORE and REPLACE INTO (two statements I heavily relied on with <em>oak-online-alter-table</em>), correctness can be achieved.</p>
<p>There's the small pain of re-generating the foreign key definition on the "ghost" table (<strong>CREATE TABLE LIKE ...</strong> does not copy FK definitions). And since foreign key names are unique, a new name must be picked up. Not pretty, but perfectly doable.</p>
<h4>"No AFTER_{INSERT/UPDATE/DELETE} triggers must exist."</h4>
<p>It would be nicer if MySQL had an ALTER TRIGGER statement. There isn't such statement. If there were such an atomic statement, then we would be able to rewrite the trigger, so as to add our own code to the <em>end of the trigger's code</em>. Yuck. Would be even nicer if we were <a href="http://code.openark.org/blog/mysql/triggers-use-case-compilation-part-ii">allowed to have multiple triggers</a> of same event.</p>
<p>So, we are left with DROP and CREATE triggers. Alas, this makes for a short period where the trigger does not exist. Bad. The easy solution would be to LOCK WRITE the table, but apparently you can't DROP the trigger (*) when the table is locked. Sigh.</p>
<p>(*) Happened to me, apparently to Facebook too; With latest 5.1 (5.1.51) version this actually works. With 5.0 it didn't use to; this needs more checking.</p>
<h4>Use of INFORMATION_SCHEMA</h4>
<p>As with oak-online-alter-table, the OSC checks for triggers, indexes, column by searching on the INFORMATION_SCHEMA tables. This makes for nice SQL for getting the exact listing and types of PRIMARY KEY columns, whether or not AFTER triggers exist, and so on.</p>
<p>I've always considered this to be the weak part of <a href="http://code.openark.org/forge/openark-kit">openark-kit</a>, that it relies on INFORMATION_SCHEMA so much. It's easier, it's cleaner, it's even <em>more correct</em> to work that way -- but it just puts too much locks. I think Baron Schwartz (and now Daniel Nichter) did amazing work on analyzing table schemata by parsing the SHOW CREATE TABLE and other SHOW commands regex-wise with <a href="http://www.maatkit.org/">Maatkit</a>. It's a crazy work! Had I written <em>openark-kit</em> in Perl, I would have just import their code. But I'm too <span style="text-decoration: line-through;">lazy</span> busy to do the conversion from Perl to Python, and rewrite that code, what with all the debugging.</p>
<p>OSC is written in PHP. Again, much conversion work. I think performance-wise this is an important step to make.</p>
<h4>A word for the critics</h4>
<p>Finally, a word for the critics. I've read some Facebook/MySQL bashing comments and wish to relate.</p>
<p>In his <a href="http://www.theregister.co.uk/2010/09/21/facebook_online_schema_change_for_mysql/">interview to The Register</a>, Mark Callaghan gave the example that "Open Schema Change lets the company update indexes without user downtime, according to Callaghan".</p>
<p>PostgreSQL was mentioned for being able to add index with only read locks taken, or being able to do the work with no locks using CREATE INDEX CONCURRENTLY. I wish MySQL had that feature! Yes, MySQL has a lot to improve upon, and the latest PostgreSQL 9.0 brings valuable new features. (Did I make it clear I have no intention of bashing PostgreSQL? If not, please re-read this paragraph until convinced).</p>
<p>Bashing related to the notion of MySQL being so poor that Facebook used an even poorer mechanism to work out the ALTER TABLE.</p>
<p>Well, allow me to add a few words: the CREATE INDEX is by far not the only thing you can achieve with OSC (although it may be Facebook's major concern). You should be able to:</p>
<ul>
<li>Add columns</li>
<li>Drop columns</li>
<li>Convert character sets</li>
<li>Modify column types</li>
<li>Add partitioning</li>
<li>Reorganize partitioning</li>
<li>Compress the table</li>
<li>Otherwise changing table format</li>
<li>Heck, you could even modify the storage engine! (To other transactional engine)</li>
</ul>
<p>These are giant steps. How easy would it be to write these down into the database? It only takes a few weeks time to work out a working solution with reasonable limitations, just using the resources the MySQL server provides you with. The <a href="http://www.facebook.com/MySQLatFacebook">MySQL@Facebook team</a> should be given credit for that.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.openark.org/blog/mysql/thoughts-and-ideas-for-online-schema-change/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>mycheckpoint (rev. 190): HTTP server; interactive charts</title>
		<link>http://code.openark.org/blog/mysql/mycheckpoint-rev-190-http-server-interactive-charts</link>
		<comments>http://code.openark.org/blog/mysql/mycheckpoint-rev-190-http-server-interactive-charts#comments</comments>
		<pubDate>Tue, 07 Sep 2010 05:53:01 +0000</pubDate>
		<dc:creator>shlomi</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Monitoring]]></category>
		<category><![CDATA[mycheckpoint]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[scripts]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://code.openark.org/blog/?p=2866</guid>
		<description><![CDATA[Revision 190 of mycheckpoint, a MySQL monitoring solution, has been released. New and updated in this revision: HTTP server: mycheckpoint can now act as a web server. Point your browser and start browsing through HTML reports. See mock up demo. Interactive charts: HTML line charts are now interactive, presenting with accurate data as you move [...]]]></description>
			<content:encoded><![CDATA[<p>Revision <strong>190</strong> of <a href="../../forge/mycheckpoint">mycheckpoint</a>, a MySQL monitoring solution, has  been released. New and updated in this revision:</p>
<ul>
<li><strong>HTTP server</strong>: <em>mycheckpoint</em> can now act as a web server. Point your browser and start browsing through HTML reports. See mock up <a href="http://code.openark.org/forge/wp-content/uploads/2010/09/r190/mcp_sql00/sv_report_html_brief.html"><strong>demo</strong></a>.</li>
<li><strong>Interactive charts</strong>: HTML line charts are now interactive, presenting with accurate data as you move over them. See <a href="http://code.openark.org/forge/wp-content/uploads/2010/09/r190/mcp_sql00_samples/sv_report_html_brief.html"><strong>sample</strong></a>.</li>
<li><strong>Enhanced auto-deploy</strong>: now auto-recognizing failed upgrades.</li>
<li><strong>Reduced footprint</strong>: much code taken out of the views, leading to faster loading times.</li>
<li><strong>Better configuration file use</strong>: now supporting all command line options in config file.</li>
<li><strong>Remote host monitoring accessibility</strong>: now supporting complete configurable accessibility details.</li>
<li><strong>Bug fixes</strong>: thanks to the bug reporters!</li>
</ul>
<p><em>mycheckpoint</em> is free, simple, easy to use (now easier with HTTP server) and <strong>useful</strong>. I encourage you to try it out: even compared with other existing and emerging monitoring tools, I believe you will find it a breeze; it's low impact and lightness appealing; it's alerts mechanism assuring; its geeky SQL-based nature with ability to drill down to fine details -- geeky-kind-of-attractive.</p>
<p>&lt;/encouragement&gt;</p>
<h4>HTTP server</h4>
<p>You can now run <em>mycheckpoint</em> in <em>http</em> mode:</p>
<blockquote>
<pre>bash$ <strong>mycheckpoint http</strong></pre>
</blockquote>
<p><em>mycheckpoint</em> will listen on port <strong>12306</strong>, and will present you with easy browsing through the reports of your <em>mycheckpoint</em> databases.<span id="more-2866"></span></p>
<p>The <em>http</em> server automatically detects those schemata used by mycheckpoint, and utilizes the existing HTML views, integrating them into the greater web framework.</p>
<p>While in <em>http</em> mode, mycheckpoint does nothing besides serving web pages. It does not actively exercise monitoring: you must still use the usual cron jobs or other scheduled tasks by which you invoke <em>mycheckpoint</em> for monitoring.</p>
<p>The http server is directed at a single MySQL server, as with the following example:</p>
<blockquote>
<pre>bash$ <strong>mycheckpoint --host=slave1.localdomain --port=3306 --http-port=12306 http</strong></pre>
</blockquote>
<p>It is assumed that this server has the monitoring schemata.</p>
<p>See mock up <a href="http://code.openark.org/forge/wp-content/uploads/2010/09/r190/mcp_sql00/sv_report_html_brief.html"><strong>demo</strong></a>. The demo uses presents with real output from a mycheckpoint HTTP server; I haven't got the means to put up a live demo.</p>
<h4>Interactive charts</h4>
<p>The <em>openark line charts</em>, used in the HTML reports, are now interactive. As you scroll over, the legend presents you with series values.</p>
<p>No more <em>"I have this huge spike once every 4 hours, which reduces all other values to something that looks like zero but is actually NOT"</em>. Hover, and see the real values.</p>
<p>See <a href="http://code.openark.org/forge/wp-content/uploads/2010/09/r190/mcp_sql00_samples/sv_report_html_brief.html"><strong>sample</strong></a>.</p>
<h4>Enhanced auto-deploy</h4>
<p>The idea with mycheckpoint is that it should know how to self upgrade the schema on version upgrade (much like automatic WordPress upgrades). mycheckpoint does bookkeeping of installed versions within the database, and upgrades by simple comparison.</p>
<p>It now, following a couple of reported bugs, also recognizes failure of partial, failed upgrades. This adds to the automation of <em>mycheckpoint</em>'s installation.</p>
<h4>Reduced footprint</h4>
<p>Some of <em>mycheckpoint</em>'s views are complicated, and lead to a large amount of code in view declaration. This leads to increased table definition size (large <strong>.frm</strong> files). There has been some work to reduce this size where possible. Work is still ongoing, but some 30% has been taken off already. This leads to faster table (view) load time.</p>
<h4>Better configuration file use</h4>
<p>Any argument supported on the command line is now also supported in the config style. Much like is handled with MySQL. For example, one can issue:</p>
<blockquote>
<pre>mycheckpoint --monitored-host=sql02.mydb.com  --monitored-user=monitor --monitored-password=123456</pre>
</blockquote>
<p>But now also:</p>
<blockquote>
<pre>mycheckpoint</pre>
</blockquote>
<p>With the following in <strong>/etc/mycheckpoint.cnf</strong>:</p>
<blockquote>
<pre>[mycheckpoint]
monitored_host     = sql02.mydb.com
monitored_user     = monitor
monitored_password = 123456
</pre>
</blockquote>
<p>Rules are:</p>
<ul>
<li>If an option is specified on command line, it takes precedence over anything else.</li>
<li>Otherwise, if it's specified in the configuration file, value is read from file.</li>
<li>Otherwise use default value is used.</li>
<li>On command line, option format is<strong> xxx-yyy-zzz</strong>: words split with dash/minus character.</li>
<li>On configuration file, option format is <strong>xxx_yyy_zzz</strong>: words split with underscore. Unlike MySQL configuration format, dashes cannot be used.</li>
<li>If an option is specified multiple times on configuration file -- well -- I have the answer, but I won't tell. Just don't do it. It's bad for your health.</li>
</ul>
<h4>Future plans</h4>
<p>Work is going on. These are the non-scheduled future tasks I see:</p>
<ul>
<li>Monitoring InnoDB Plugin &amp; XtraDB status.</li>
<li>A proper <em>man</em> page.</li>
<li>Anything else that interests me &amp; the users.</li>
</ul>
<h4>Try it out</h4>
<p>Try out <em>mycheckpoint</em>. It’s a different kind of monitoring   solution. Simple monitoring (charting) is immediate. For more interesting results you will need basic SQL skills, and in return you’ll get a lot   of power under your hands.</p>
<ul>
<li>Download mycheckpoint <a href="https://code.google.com/p/mycheckpoint/">here</a></li>
<li>Visit the project’s <a href="../../forge/mycheckpoint">homepage</a></li>
<li>Browse the <a href="../../forge/mycheckpoint/documentation">documentation</a></li>
<li>Report <a href="https://code.google.com/p/mycheckpoint/issues/list">bugs</a></li>
</ul>
<p><em>mycheckpoint</em> is released under the <a href="http://www.opensource.org/licenses/bsd-license.php">New BSD  License</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.openark.org/blog/mysql/mycheckpoint-rev-190-http-server-interactive-charts/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Another Python MySQL template</title>
		<link>http://code.openark.org/blog/mysql/another-python-mysql-template</link>
		<comments>http://code.openark.org/blog/mysql/another-python-mysql-template#comments</comments>
		<pubDate>Wed, 11 Aug 2010 05:51:57 +0000</pubDate>
		<dc:creator>shlomi</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[scripts]]></category>

		<guid isPermaLink="false">http://code.openark.org/blog/?p=2815</guid>
		<description><![CDATA[Following up on Matt Reid's simple python, mysql connection and iteration, I would like to share one of my own, which is the base for mycheckpoint &#38; openark kit scripts. It is oriented to provide with clean access to the data: the user is not expected to handle cursors and connections. Result sets are returned [...]]]></description>
			<content:encoded><![CDATA[<p>Following up on Matt Reid's <a href="http://themattreid.com/wordpress/?p=330">simple python, mysql connection and iteration</a>, I would like to share one of my own, which is the base for mycheckpoint &amp; openark kit scripts.</p>
<p>It is oriented to provide with clean access to the data: the user is not expected to handle cursors and connections. Result sets are returned as python lists and dictionaries. It is also config file aware and comes with built in command line options.</p>
<p>I hope it comes to use: <a href="http://code.openark.org/blog/wp-content/uploads/2010/08/my.py">my.py</a></p>
]]></content:encoded>
			<wfw:commentRss>http://code.openark.org/blog/mysql/another-python-mysql-template/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>mycheckpoint (rev. 132): custom monitoring, custom charts, process list dump</title>
		<link>http://code.openark.org/blog/mysql/mycheckpoint-rev-132-custom-monitoring-custom-charts-process-list-dump</link>
		<comments>http://code.openark.org/blog/mysql/mycheckpoint-rev-132-custom-monitoring-custom-charts-process-list-dump#comments</comments>
		<pubDate>Fri, 04 Jun 2010 09:17:27 +0000</pubDate>
		<dc:creator>shlomi</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Monitoring]]></category>
		<category><![CDATA[mycheckpoint]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[scripts]]></category>

		<guid isPermaLink="false">http://code.openark.org/blog/?p=2463</guid>
		<description><![CDATA[Revision 132 of mycheckpoint has been released. New and updated in this revision: Custom monitoring: monitoring &#38; charting for user defined queries HTML reports for custom monitoring Process list dump upon alert notifications Custom monitoring &#38; charts Custom monitoring allows the user to supply with a query, the results of which will be monitored. That [...]]]></description>
			<content:encoded><![CDATA[<p>Revision <strong>132</strong> of <a href="../../forge/mycheckpoint">mycheckpoint</a> has been released. New and updated in this revision:</p>
<ul>
<li>Custom monitoring: monitoring &amp; charting for user defined queries</li>
<li>HTML reports for custom monitoring</li>
<li>Process list dump upon alert notifications</li>
</ul>
<h4>Custom monitoring &amp; charts</h4>
<p>Custom monitoring allows the user to supply with a query, the results of which will be monitored.</p>
<p>That is, <em>mycheckpoint</em> monitors the status variables, replication status, OS metrics. But it cannot by itself monitor one's <em>application</em>. Which is why a user may supply with such query as:</p>
<blockquote><pre class="brush: sql; title: ; notranslate">
SELECT COUNT(*) FROM shopping_cart WHERE is_pending=1
</pre>
</blockquote>
<p>Such a query will tell an online store how many customers are in the midst of shopping. There is no argument that this number is worth monitoring for. Given the above query, <em>mycheckpoint</em> will execute it per sample, and store the query's result along with all sampled data, to be then aggregated by complex views to answer for:</p>
<ul>
<li>What was the value per given sample?</li>
<li>What is the value difference for each sample?</li>
<li>What is the change per second, i.e. the rate?</li>
</ul>
<p>mycheckpoint goes one step forward, and explicity records another metric:</p>
<ul>
<li>How much time did it take to take that sample?</li>
</ul>
<p><span id="more-2463"></span>As another example, a query worth testing for rate:</p>
<blockquote><pre class="brush: sql; title: ; notranslate">
SELECT MAX(shopping_cart_id) FROM shopping_cart
</pre>
</blockquote>
<p>The above will provide with the last id. Assuming this is <strong>AUTO_INCREMENT</strong>, and assuming we're on <strong>auto_increment_increment=1</strong>, two samples will allow us to get the number of created carts between those samples. Now, here's a metric I'd like to read:</p>
<ul>
<li>How many carts are created per second, for each hour of the day?</li>
</ul>
<p>We get all these for free with mycheckpoint, which already does this analysis. All we need to provide is the query, and how we would like it to be visualized (visualization is optional, it is not the only way to diagnose monitored data) graphically:</p>
<blockquote><pre class="brush: sql; title: ; notranslate">
INSERT INTO
 custom_query (custom_query_id, enabled, query_eval, description, chart_type, chart_order)
 VALUES (0, 1, 'SELECT COUNT(*) FROM store.shopping_cart WHERE is_pending=1', 'Number of pending carts', 'value', 0);

INSERT INTO
 custom_query (custom_query_id, enabled, query_eval, description, chart_type, chart_order)
 VALUES (1, 1, 'SELECT MAX(shopping_cart_id) FROM store.shopping_cart', 'Created carts rate', 'value_psec', 0);
</pre>
</blockquote>
<p>We can later query for these values, just like we do for normal monitored values:</p>
<blockquote><pre class="brush: sql; title: ; notranslate">
mysql&gt; SELECT id, ts, created_tmp_tables_psec, custom_0, custom_1_psec FROM sv_sample WHERE ts &gt;= NOW() - INTERVAL 1 HOUR;
+-------+---------------------+-------------------------+----------+---------------+
| id    | ts                  | created_tmp_tables_psec | custom_0 | custom_1_psec |
+-------+---------------------+-------------------------+----------+---------------+
| 50730 | 2010-05-21 19:05:01 |                   16.64 |      448 |          3.02 |
| 50731 | 2010-05-21 19:10:02 |                   20.97 |       89 |          1.73 |
| 50732 | 2010-05-21 19:15:01 |                   15.70 |      367 |          3.56 |
| 50733 | 2010-05-21 19:20:01 |                   18.32 |       54 |          1.43 |
| 50734 | 2010-05-21 19:25:01 |                   16.42 |       91 |          1.96 |
| 50735 | 2010-05-21 19:30:02 |                   21.93 |      233 |          2.11 |
| 50736 | 2010-05-21 19:35:02 |                   14.58 |      176 |          1.91 |
| 50737 | 2010-05-21 19:40:01 |                   21.61 |      168 |          1.93 |
| 50738 | 2010-05-21 19:45:01 |                   16.05 |      241 |          2.44 |
| 50739 | 2010-05-21 19:50:01 |                   19.70 |       46 |          1.19 |
| 50740 | 2010-05-21 19:55:01 |                   15.85 |      177 |          2.28 |
| 50741 | 2010-05-21 20:00:01 |                   19.04 |        8 |          0.82 |
+-------+---------------------+-------------------------+----------+---------------+
</pre>
</blockquote>
<p>Of course, it is also possible to harness <em>mycheckpoint</em>'s views power to generate charts:</p>
<blockquote>
<pre>mysql&gt; SELECT custom_1_psec FROM sv_report_chart_sample\G
<img class="alignnone" title="custom_1_psec" src="http://chart.apis.google.com/chart?cht=lc&amp;chs=400x200&amp;chts=303030,12&amp;chtt=Latest+24+hours:+May+19,+20:10++-++May+20,+20:10&amp;chf=c,s,ffffff&amp;chdl=custom_1_psec&amp;chdlp=b&amp;chco=ff8c00&amp;chd=s:QfXQmZQhXTmWVkWRobPpWUtQPVROaOOUMJPOKdJHQJFJEDJJEGCAIEFJHFFEGGDQHGJGMJPPMNZNRWR_ZUWfR_nSjuUcaXa3OgxRl4UivWZ5UhtWX4VgnUTYktiVW9WanUVxVYlgXwVdicXpb&amp;chxt=x,y&amp;chxr=1,0,5.120000&amp;chxl=0:||+||00:00||+||04:00||+||08:00||+||12:00||+||16:00||+||20:00|&amp;chxs=0,505050,10,0,lt&amp;chg=4.17,25,1,2,3.47,0&amp;chxp=0,3.47,7.64,11.81,15.98,20.15,24.32,28.49,32.66,36.83,41.00,45.17,49.34,53.51,57.68,61.85,66.02,70.19,74.36,78.53,82.70,86.87,91.04,95.21,99.38" alt="" width="400" height="200" />
</pre>
</blockquote>
<p>The rules are:</p>
<ul>
<li>There can (currently) only be 18 custom queries.</li>
<li>The <strong>custom_query_id</strong> must range 0-17 (to be lifted soon).</li>
<li>A custom query must return with <em>exactly</em> one row, with <em>exactly</em> one column, which is a kind of <em>integer</em>.</li>
</ul>
<p>Please read <a href="http://code.openark.org/blog/mysql/things-to-monitor-on-mysql-the-users-perspective">my earlier post</a> on custom monitoring to get more background.</p>
<h4>Custom monitoring HTML reports</h4>
<p>Custom monitoring comes with a HTML reports, featuring requested charts. See a <a href="http://code.openark.org/blog/wp-content/uploads/2010/05/mcp_custom_report-128.html">sample custom report</a>.</p>
<p>In this sample report, a few queries are monitored for value (pending rentals, pending downloads) and a few for rates (downloads per second, emails per second etc.).</p>
<p>Custom HTML reports come in two flavors:</p>
<ul>
<li>Brief reports, featuring last 24 hours, as in the example above. These are handled by the <strong>sv_custom_html_brief</strong> view.</li>
<li>Full reports, featuring last 24 hours, last 10 days, known history. These take longer to generate, and are handled by the <strong>sv_custom_html</strong> view.</li>
</ul>
<p>The sample report was generated by issuing:</p>
<blockquote>
<pre>SELECT html FROM sv_custom_html_brief;</pre>
</blockquote>
<p>I won't go into details here as for how this view generates the HTML code. There is a myriad of view dependencies, with many interesting tricks on the way. But do remember it's <em>just a view</em>. You don't need an application (not even <em>mycheckpoint</em> itself) to generate the report. All it takes is a query.</p>
<h4>Processlist dump</h4>
<p>When an alert notification fires (an email is prepared to inform on some alert condition), a processlist dump summary is taken and included in email report. It may be useful to understand why the slave is lagging, or exactly why there are so many active threads.</p>
<p>The dump summary presents the processlist much as you would see it on SHOW PROCESSLIST, but only lists the active threads, noting down how many sleeping processes there are (PS, thread &amp; process are the same in the terminology of MySQL connections). An example dump looks like this:</p>
<blockquote>
<pre>PROCESSLIST summary:

     Id: 3
   User: system user
   Host:
     db: NULL
Command: Connect
   Time: 3168098
  State: Waiting for master to send event
   Info: NULL
-------

     Id: 4
   User: system user
   Host:
     db: prod_db
Command: Connect
   Time: 612
  State: Updating
   Info: UPDATE user SET is_offline = 1 WHERE id IN (50440010,50440011)
-------

     Id: 8916579
   User: prod_user
   Host: localhost
     db: prod_db
Command: Query
   Time: 1
  State: Sending data
   Info: INSERT IGNORE INTO archive.stat_archive (id, origin, path, ts, content
-------

     Id: 8916629
   User: mycheckpoint
   Host: localhost
     db: NULL
Command: Query
   Time: 0
  State: NULL
   Info: SHOW PROCESSLIST
-------
Sleeping: 3 processes
</pre>
</blockquote>
<h4>Future plans</h4>
<p>Work is going on. These are the non-scheduled future tasks I see:</p>
<ul>
<li>Monitoring InnoDB Plugin &amp; XtraDB status.</li>
<li>Interactive charts. See my <a href="http://code.openark.org/blog/mysql/static-charts-vs-interactive-charts">earlier post</a>.</li>
<li>Monitoring for swap activity (Linux only).</li>
<li>Enhanced custom queries handling, including auto-deploy upon change of custom queries.</li>
<li>A proper <em>man</em> page.</li>
<li>Anything else that interests me.</li>
</ul>
<h4>Try it out</h4>
<p>Try out <em>mycheckpoint</em>. It’s a different kind of monitoring solution. You will need basic SQL skills, and in return you'll get a lot of power under your hands.</p>
<ul>
<li>Download mycheckpoint <a href="https://code.google.com/p/mycheckpoint/">here</a></li>
<li>Visit the project’s <a href="../../forge/mycheckpoint">homepage</a></li>
<li>Browse the <a href="../../forge/mycheckpoint/documentation">documentation</a></li>
<li>Report <a href="https://code.google.com/p/mycheckpoint/issues/list">bugs</a></li>
</ul>
<p><em>mycheckpoint</em> is released under the <a href="http://www.opensource.org/licenses/bsd-license.php">New BSD License</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.openark.org/blog/mysql/mycheckpoint-rev-132-custom-monitoring-custom-charts-process-list-dump/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>mycheckpoint (Rev. 118): alerts, email notifications and more</title>
		<link>http://code.openark.org/blog/mysql/mycheckpoint-rev-118-alerts-email-notifications-and-more</link>
		<comments>http://code.openark.org/blog/mysql/mycheckpoint-rev-118-alerts-email-notifications-and-more#comments</comments>
		<pubDate>Thu, 25 Mar 2010 06:26:34 +0000</pubDate>
		<dc:creator>shlomi</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Monitoring]]></category>
		<category><![CDATA[mycheckpoint]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://code.openark.org/blog/?p=2221</guid>
		<description><![CDATA[Revision 118 of mycheckpoint has been released. New and updated in this revision: Conditional alerts Email notifications Revised HTML reports, including 24/7 reports. Updated documentation With this new revision mycheckpoint turns into a monitoring solution for MySQL. One can now: Store measure metrics Query for raw, aggregated or digested metrics Generate charts for selected metrics [...]]]></description>
			<content:encoded><![CDATA[<p>Revision <strong>118</strong> of <a href="http://code.openark.org/forge/mycheckpoint">mycheckpoint</a> has been released. New and updated in this revision:</p>
<ul>
<li>Conditional alerts</li>
<li>Email notifications</li>
<li>Revised HTML reports, including 24/7 reports.</li>
<li>Updated documentation</li>
</ul>
<p>With this new revision mycheckpoint turns into a <em>monitoring solution</em> for MySQL. One can now:</p>
<ul>
<li>Store measure metrics</li>
<li>Query for raw, aggregated or digested metrics</li>
<li>Generate charts for selected metrics</li>
<li>View HTML reports for selecetd metrics</li>
<li>Define alerts conditions, query for pending alerts</li>
<li>Be notified via <em>email</em> on <em>raised</em> or <em>resolved</em> alerts.</li>
</ul>
<h4>Conditional alerts</h4>
<p><em>mycheckpoint</em> is <em>SQL oriented</em>. As such, it allows for creation of alert conditions, which are nothing more than SQL conditions.</p>
<p><span id="more-2221"></span>For example, we wish to raise an alerts when the slave stops replicating (just ping us with an email one this happens):</p>
<blockquote><pre class="brush: sql; title: ; notranslate">INSERT INTO alert_condition (condition_eval, description, alert_delay_minutes)
  VALUES ('seconds_behind_master IS NULL', 'Slave not replicating', 0);</pre>
</blockquote>
<p>Or is too far behind (but since we do maintenance work during the night, it's OK on those hours). We only want to be notified if this goes on for <strong>10</strong> minutes:</p>
<blockquote><pre class="brush: sql; title: ; notranslate">INSERT INTO alert_condition (condition_eval, description, alert_delay_minutes)
  VALUES ('(seconds_behind_master &gt; 60) AND (HOUR(ts) NOT BETWEEN 2 AND 4)', 'Slave lags too far behind', 10);</pre>
</blockquote>
<p>We want to be notified when the <strong>datadir</strong> mount point disk quota exceeds 95% usage. Oh, and please keep nagging us about this, as long as it is unresolved:</p>
<blockquote><pre class="brush: sql; title: ; notranslate">INSERT INTO alert_condition (condition_eval, description, repetitive_alert)
  VALUES ('os_datadir_mountpoint_usage_percent &gt; 95', 'datadir mount point is over 95%', 1);</pre>
</blockquote>
<p>There's much more to alert conditions. You can generate a pending alerts report, get a textual presentation of raised and pending alerts, view the query which determines what alerts are currently raised, and more.</p>
<p>Read more on the <a href="http://code.openark.org/forge/mycheckpoint/documentation/alerts">alerts documentation page</a>.</p>
<h4>Email notifications</h4>
<p>Introducing email notifications, <em>mycheckpoint</em> now:</p>
<ul>
<li>Sends email notification on alert conditions meeting. See <a href="http://code.openark.org/forge/wp-content/uploads/2010/03/mycheckpoint-alerts-email-sample-113.jpeg">sample email screenshot</a>.</li>
<li>Sends email notification when it is unable to access the database.</li>
<li>Sends report via mail. Currently only HTML brief report is supported. Report is attached as HTML file in email message.</li>
</ul>
<p>Alert notifications are automatically sent by mail (once SMTP configuration is in place, see following) when an alert is <em>raised</em> (alert condition becomes <strong>true</strong>) or <em>resolved</em> (alert condition turns <strong>false</strong>).</p>
<p>Email notifications require simple configuration for SMTP host, SMTP-from-address, SMTP-to-address. These can be made in the <a href="http://code.openark.org/forge/mycheckpoint/documentation/usage#defaults_file">defaults file</a> (revised), or through the command line. The following example shows how one can manually send an HTML brief report:</p>
<blockquote>
<pre>mycheckpoint --defaults-file=/etc/mycheckpoint.cnf <strong>--smtp-from</strong>=monitor@my-server-company.com <strong>--smtp-to</strong>=dba@my-server-company.com <strong>--smtp-host</strong>=mail.my-server-company.com <strong>email_brief_report</strong></pre>
</blockquote>
<p>One should generally set up these parameters in the configuration file (aka <em>defaults file</em>) and forget all about it. mycheckpoint now has a default for the defaults file, which is <strong>/etc/mycheckpoint.cnf</strong>.</p>
<p>Read more on the <a href="http://code.openark.org/forge/mycheckpoint/documentation/emails">emails documentation page</a>.</p>
<h4>Revised HTML reports</h4>
<ul>
<li>The brief HTML reports has been updated, see <a href="http://code.openark.org/forge/wp-content/uploads/2010/03/mycheckpoint-brief-report-sample-113.html">sample</a>.</li>
<li>An HTML 24/7 report as been added, see <a href="../../forge/wp-content/uploads/2010/03/mycheckpoint-24-7-report-sample-107.html">sample</a>. This report shows the distribution of popular metrics throughout the weekdays and hours.</li>
</ul>
<p>Full HTML reports remain slow to load. I'm putting some work into this, but I'm not sure I can work around the optimizer's limitations of using indexes for GROUPing through views.</p>
<h4>Updated documentation</h4>
<p>The documentation has been revised, with more details put into the pages. Since <em>mycheckpoint</em> gains more and more features, I saw fit to write a <a href="http://code.openark.org/forge/mycheckpoint/documentation/quick-howto">Quick HOWTO</a> page which gets you up to speed, no fuss around, with <em>mycheckpoint</em>'s usage and features.</p>
<p>Read the mycheckpoint <a href="http://code.openark.org/forge/mycheckpoint/documentation/quick-howto">Quick HOWTO</a> here.</p>
<h4>Future plans</h4>
<p>Work is going on. These are the non-scheduled future tasks I see:</p>
<ul>
<li>Custom monitoring + notifications. See my <a href="http://code.openark.org/blog/mysql/things-to-monitor-on-mysql-the-users-perspective">earlier post</a>.</li>
<li>Monitoring InnoDB Plugin &amp; XtraDB status.</li>
<li>PROCESSLIST dump on alerts.</li>
<li>Interactive charts. See my <a href="http://code.openark.org/blog/mysql/static-charts-vs-interactive-charts">earlier post</a>.</li>
<li>A proper <em>man</em> page...</li>
</ul>
<h4>Try it out</h4>
<p>Try out <em>mycheckpoint</em>. It's a different kind of monitoring solution. It does not require to to have a web server or complicated dependencies. To the experienced DBA it can further provide with valuable, raw or digested information in the form of SQL accessible data. I have used it to find anomalies in passing months, doing SQL search for periods of time where several conditions applied -- it really gives you some extra power.</p>
<ul>
<li>Download mycheckpoint <a href="https://code.google.com/p/mycheckpoint/">here</a></li>
<li>Visit the project's <a href="http://code.openark.org/forge/mycheckpoint">homepage</a></li>
<li>Browse the <a href="http://code.openark.org/forge/mycheckpoint/documentation">documentation</a></li>
<li>Report <a href="https://code.google.com/p/mycheckpoint/issues/list">bugs</a></li>
</ul>
<p><em>mycheckpoint</em> is released under the <a href="http://www.opensource.org/licenses/bsd-license.php">New BSD License</a>.</p>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 855px; width: 1px; height: 1px;">http://code.openark.org/forge/mycheckpoint/documentation/quick-howto</div>
]]></content:encoded>
			<wfw:commentRss>http://code.openark.org/blog/mysql/mycheckpoint-rev-118-alerts-email-notifications-and-more/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>oak-hook-general-log: streaming general log</title>
		<link>http://code.openark.org/blog/mysql/oak-hook-general-log-streaming-general-log</link>
		<comments>http://code.openark.org/blog/mysql/oak-hook-general-log-streaming-general-log#comments</comments>
		<pubDate>Sun, 21 Mar 2010 08:45:58 +0000</pubDate>
		<dc:creator>shlomi</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[logs]]></category>
		<category><![CDATA[openark kit]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[scripts]]></category>

		<guid isPermaLink="false">http://code.openark.org/blog/?p=2253</guid>
		<description><![CDATA[I'm seeking input on a new openark kit utility I've started to implement. The tool, oak-hook-general-log, will hook up to a MySQL (&#62;= 5.1) server, and stream the general log into standard output. It looks like this: bash$ python src/oak/oak-hook-general-log.py --socket=/tmp/mysql.sock --user=root 2010-03-21 10:18:42     root[root] @ localhost []       79      1       Query   SELECT COUNT(*) FROM City [...]]]></description>
			<content:encoded><![CDATA[<p>I'm seeking input on a new <a href="http://code.openark.org/forge/openark-kit">openark kit</a> utility I've started to implement.</p>
<p>The tool, <strong>oak-hook-general-log</strong>, will hook up to a MySQL (&gt;= 5.1) server, and stream the general log into standard output. It looks like this:</p>
<blockquote>
<pre>bash$ python src/oak/oak-hook-general-log.py --socket=/tmp/mysql.sock --user=root
2010-03-21 10:18:42     root[root] @ localhost []       79      1       Query   SELECT COUNT(*) FROM City
2010-03-21 10:18:48     root[root] @ localhost []       79      1       Query   DELETE FROM City WHERE id=1000
2010-03-21 10:18:54     root[root] @ localhost []       79      1       Query   SHOW PROCESSLIST
2010-03-21 10:19:06     root[root] @ localhost []       79      1       Quit
2010-03-21 10:19:07     root[root] @ localhost []       93      1       Connect root@localhost on
2010-03-21 10:19:07     root[root] @ localhost []       93      1       Query   select @@version_comment limit 1
2010-03-21 10:22:33     root[root] @ localhost []       93      1       Query   SELECT City.Name, Country.Name FROM Country JOIN City ON Country.Capit
2010-03-21 10:22:58     root[root] @ localhost []       93      1       Quit
</pre>
</blockquote>
<p>Since output is written to <strong>stdout</strong>, one can further:</p>
<blockquote>
<pre>bash$ python src/oak/oak-hook-general-log.py --socket=/tmp/mysql.sock --user=root | grep Connect
bash$ python src/oak/oak-hook-general-log.py --socket=/tmp/mysql.sock --user=root | grep webuser@webhost</pre>
</blockquote>
<p>What the tool does is to enable table logs, and periodically rotate the <strong>mysql.general_log</strong> table, read and dump its content.</p>
<p><span id="more-2253"></span>The tool:</p>
<ul>
<li>Stores and restores the original log state (general log enabled/disabled, log output).</li>
<li>Disables printing of its own queries to the general log.</li>
<li>Automatically times out (timeout configurable) so as not to enter a situation where the general log is forgotten to be turned on.</li>
<li>Can discard pre-existing data on the <strong>mysql.general_log</strong> table.</li>
<li>Will cleanup the <strong>mysql.slow_log</strong> table, if it wasn't originally used (turning on table logs applies to both general log and slow log).</li>
</ul>
<p>What would you have the tool do further? Should it provide filtering, or should we just use <strong>grep</strong>/<strong>sed</strong>/<strong>awk</strong> for that? Any internal aggregation of data?</p>
<p>I would love to hear your thoughts. Meanwhile, <a href="http://code.google.com/p/openarkkit/source/browse/trunk/openarkkit/src/oak/oak-hook-general-log.py">view or grab the python script file</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.openark.org/blog/mysql/oak-hook-general-log-streaming-general-log/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Proper SQL table alias use conventions</title>
		<link>http://code.openark.org/blog/mysql/proper-sql-table-alias-use-conventions</link>
		<comments>http://code.openark.org/blog/mysql/proper-sql-table-alias-use-conventions#comments</comments>
		<pubDate>Thu, 11 Mar 2010 07:10:09 +0000</pubDate>
		<dc:creator>shlomi</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Opinions]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Syntax]]></category>

		<guid isPermaLink="false">http://code.openark.org/blog/?p=2156</guid>
		<description><![CDATA[After seeing quite some SQL statements over the years, something is bugging me: there is no consistent convention as for how to write an SQL query. I'm going to leave formatting, upper/lower-case issues aside, and discuss a small part of the SQL syntax: table aliases. Looking at three different queries, I will describe what I [...]]]></description>
			<content:encoded><![CDATA[<p>After seeing quite some SQL statements over the years, something is bugging me: there is no consistent convention as for how to write an SQL query.</p>
<p>I'm going to leave formatting, upper/lower-case issues aside, and discuss a small part of the SQL syntax: table aliases. Looking at three different queries, I will describe what I find to be problematic table alias use.</p>
<p>Using the <a href="http://dev.mysql.com/doc/sakila/en/sakila.html">sakila</a> database, take a look at the following queries:<span id="more-2156"></span></p>
<h4>Query #1</h4>
<blockquote>
<pre><strong>SELECT</strong>
 R.rental_date, C.customer_id, C.first_name, C.last_name
<strong>FROM</strong>
 rental R
 <strong>JOIN</strong> customer C <strong>USING</strong> (customer_id)
<strong>WHERE</strong>
 R.rental_date &gt;= DATE('2005-10-01')
 <strong>AND</strong> C.store_id=1;
</pre>
</blockquote>
<p>The above looks for film rentals done in a specific store (store #<strong>1</strong>), as of Oct. 1st, 2005.</p>
<h4>Query #2</h4>
<blockquote>
<pre><strong>SELECT</strong>
 F.title, C.name
<strong>FROM</strong>
 film <strong>AS</strong> F
 <strong>JOIN</strong> film_category <strong>AS</strong> S <strong>ON</strong> (F.film_id = S.film_id)
 <strong>JOIN</strong> category <strong>AS</strong> C <strong>ON</strong> (S.category_id = C.category_id)
<strong>WHERE</strong> F.length &gt; 180;</pre>
</blockquote>
<p>The above lists the title and category for all films longer than three hours.</p>
<h4>Query #3</h4>
<blockquote>
<pre><strong>SELECT</strong> c.customer_id, c.last_name
<strong>FROM</strong>
  customer c
  <strong>INNER JOIN</strong> address a ON (c.address_id = a.address_id)
  <strong>INNER JOIN</strong> (
    <strong>SELECT</strong>
      c.city_id
    <strong>FROM</strong>
      city AS c
      <strong>JOIN</strong> country s <strong>ON</strong> (c.country_id = s.country_id)
    <strong>WHERE</strong>
      s.country <strong>LIKE</strong> 'F%'
  ) s1 <strong>USING</strong> (city_id)
<strong>WHERE</strong>
  create_date &gt;= DATE('2005-10-01');
</pre>
</blockquote>
<p>The above lists customers created as of Oct. 1st, 2005, and who live in countries starting with an 'F'. The query could be solved without a subquery, but there's a good reason why I made it so.</p>
<h4>The problems</h4>
<p>I used very different conventions on any one of the queries, and sometimes within each query. And it's common that I see the same on a customer's site, what with having many programmers do the SQL coding. Again, I will only discuss the table aliases conventions. I'll leaver the rest to the reader.</p>
<p>Here's where I see problems:</p>
<ul>
<li>Query <strong>#1</strong>: In itself, it looks fine. <strong>Rental</strong> turns to <strong>R</strong>, <strong>Customer</strong> turns to <strong>C</strong>. I will comment on this slightly later on when I provide my full opinion.</li>
<li>Query <strong>#2</strong>: So <strong>film</strong> turns to <strong>F</strong>, <strong>category</strong> turns to <strong>C</strong>. What should <strong>film_category</strong> turn into? <em>Out of letters?</em> Let's just go for <strong>S</strong>, shall we? But <strong>S</strong> has nothing do with <strong>film_category</strong>. Yet it's so commonly seen.</li>
<li>Query <strong>#2</strong>: We're using the <strong>AS</strong> keyword now. We didn't use it before.</li>
<li>Queries <strong>#1</strong>, <strong>#2</strong>: Hold on. Wasn't <strong>C</strong> taken for <strong>customer</strong> in Query <strong>#1</strong>? Now, in Query <strong>#2</strong> it stands for <strong>category</strong>? I'm beginning to get confused.</li>
<li>Query <strong>#3</strong>: Now aliases are lower case; I was just getting used to them being upper case.</li>
<li>Query <strong>#3</strong>: But, hey, <strong>c</strong> is back to <strong>customer</strong>!</li>
<li>Query <strong>#3</strong>: Or, is it? Take a look at the subquery. Theres another <strong>c</strong> in there! This time it's <strong>city</strong>! And it's perfectly valid syntax. We actually have two identical aliases in the same query.</li>
<li>Query <strong>#3</strong>: If I could, I would name country with <strong>c</strong> as well. But I can't. So why not throw in <strong>s</strong> again?</li>
<li>Query <strong>#3</strong>: and now I don't even bother using the alias when accessing the <strong>create_date</strong>. Well, there's no such column in any of the other tables!</li>
</ul>
<h4>Proper conventions</h4>
<p>What I find so disturbing is that whenever I read a complex query, I need to go back and forth, back and forth between table aliases (found everywhere in the query) and their declaration point. Such irregularities make the queries difficult to read.</p>
<p>Any of the above issues could be justified. But I wish to make some suggestions:</p>
<ul>
<li>Decide whether you're going for upper or lower case.</li>
<li>Do not use the same alias twice in your query, even if it's valid.</li>
<li>Aliases do not have to be single character. <strong>film_category</strong> may just as well be <strong>FC</strong>.</li>
<li>Do not alias something that is hard to interpret. <strong>s</strong> does not stand for <strong>country</strong>.</li>
<li>Think ahead: use same aliases throughout all your queries, as far as you can. If uniqueness is a problem, make for longer aliases. Use <strong>cust</strong> instead of <strong>c</strong>.</li>
</ul>
<p>The above should make for more organized and readable SQL code. Remember: what one programmer finds as a very intuitive alias, is unintuitive to another!</p>
<h4>My own convention</h4>
<p>Simple: I <em>only use aliases</em> when using self joins. I am aware that queries are much longer what with long table names. I go farther than that: I prefer fully qualifying questionable columns throughout the query. Yes, it makes the query even longer.</p>
<p>I know this does not appeal to many. But there's no confusion. And it's easily searchable. And it's consistent. And if properly formatted, as in the above queries, is well readable.</p>
<p>Now please join me in asking Oracle if they can add multi-line Strings for java, as there are for python.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.openark.org/blog/mysql/proper-sql-table-alias-use-conventions/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

