<?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>Experimental Thoughts &#187; Language</title>
	<atom:link href="http://thoughts.j-davis.com/category/language/feed/" rel="self" type="application/rss+xml" />
	<link>http://thoughts.j-davis.com</link>
	<description>Ideas on Databases, Logic, and Language by Jeff Davis</description>
	<lastBuildDate>Thu, 06 May 2010 19:29:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Flexible Schemas and PostgreSQL</title>
		<link>http://thoughts.j-davis.com/2010/05/06/flexible-schemas-and-postgresql/</link>
		<comments>http://thoughts.j-davis.com/2010/05/06/flexible-schemas-and-postgresql/#comments</comments>
		<pubDate>Thu, 06 May 2010 17:42:28 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[NULL]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://thoughts.j-davis.com/?p=267</guid>
		<description><![CDATA[First, what is a &#8220;flexible schema&#8221;? It&#8217;s hard to pin down an exact definition, but it&#8217;s used to mean a data model that permits changes in application data structures without needing to migrate old data or incur other administrative hassles. That&#8217;s a worthwhile goal. Applications often grow organically, especially in the early, exploratory stages of [...]]]></description>
			<content:encoded><![CDATA[<p>First, what is a &#8220;flexible schema&#8221;? It&#8217;s hard to pin down an exact definition, but it&#8217;s used to mean a data model that permits changes in application data structures without needing to migrate old data or incur other administrative hassles.</p>
<p>That&#8217;s a worthwhile goal. Applications often grow organically, especially in the early, exploratory stages of development. For example, you may decide to track when a user last did something on the website, so that you can adapt news and notices for those users (e.g. &#8220;Did you know that we added feature XYZ since you last visited?&#8221;). Developers have a need to produce a prototype quickly to work out the edge cases (do we update that timestamp for all actions, or only certain ones?), and probably a need to put it in production so that the users can benefit sooner.</p>
<p>A common worry is that <code>ALTER TABLE</code> will be a major performance problem. That&#8217;s sometimes a problem, but in PostgreSQL, you can add a column to a table in constant time (not dependent on the size of the table) in most situations. I don&#8217;t think this is a good reason to avoid <code>ALTER TABLE</code>, at least in PostgreSQL (other systems may impose a greater burden).</p>
<p>There are good reasons to avoid <code>ALTER TABLE</code>, however. We&#8217;ve only defined one use case for this new &#8220;last updated&#8221; field, and it&#8217;s a fairly loose definition. If we use <code>ALTER TABLE</code> as a first reaction for tracking any new application state, we&#8217;d end up with lots of columns with overlapping meanings (all subtly different), and it would be challenging to keep them consistent with each other. More importantly, adding new columns without thinking through the meaning and the data migration strategy will surely cause confusion and bugs. For example, if you see the following table:</p>
<pre>    CREATE TABLE users
    (
      name         TEXT,
      email        TEXT,
      ...,
      last_updated TIMESTAMPTZ
    );
</pre>
<p>you might (reasonably) assume that the following query makes sense:</p>
<pre>    SELECT * FROM users
      WHERE last_updated &lt; NOW() - '1 month'::INTERVAL;</pre>
<p>Can you spot the problem? Old user records (before the <code>ALTER TABLE</code>) will have <code>NULL</code> for <code>last_updated</code> timestamps, and will not satisfy the <code>WHERE</code> condition even though they intuitively qualify. There are two parts to the problem:</p>
<ol>
<li>The presence of the <code>last_updated</code> field fools the author of the SQL query into making assumptions about the data, because it seems so simple on the surface.</li>
<li>NULL semantics allow the query to be executed even without complete information, leading to a wrong result.</li>
</ol>
<p>Let&#8217;s try changing the table definition:</p>
<pre>    CREATE TABLE users
    (
      name       TEXT,
      email      TEXT,
      ...,
      properties HSTORE
    );
</pre>
<p><a title="HSTORE" href="http://www.postgresql.org/docs/8.4/static/hstore.html">HSTORE</a> is a set of key/value pairs. Some tuples might have the <code>last_updated</code> key in the properties attribute, and others may not. This accomplishes two things:</p>
<ol>
<li>There&#8217;s no need for ALTER TABLE or cluttering of the namespace with a lot of nullable columns.</li>
<li>The name &#8220;properties&#8221; is vague enough that query writers would (hopefully) be on their guard, understanding that not all records will share the same properties.</li>
</ol>
<p>You could still write the same (wrong) query against the second table with minor modification. Nothing has fundamentally changed. But we are using a different development strategy that&#8217;s easy on application developers during rapid development cycles, yet does not leave a series of pitfalls for users of the data. When a certain property becomes universally recorded and has a concrete meaning, you can plan a real data migration to turn it into a relation attribute instead.</p>
<p>Now, we need some guiding principles about when to use a complex type to  represent complex information, and when to use separate columns in the  table. To maximize utility and minimize confusion, I believe the best  guiding principle is the meaning of the data you&#8217;re storing across <em>all </em>tuples. When defining the attributes of a relation, if you find  yourself using vague nouns such as &#8220;properties,&#8221; or resorting to complex  qualifications (lots of &#8220;if/then&#8221; branching in your definition), consider less constrained data types like <a title="HSTORE" href="http://www.postgresql.org/docs/8.4/static/hstore.html">HSTORE</a>.  Otherwise, it&#8217;s best to nail down the meaning in terms of appropriate  nouns, which will help keep the DBMS smart and queries simple (and correct). See <a title="Choosing Data Types" href="../2009/09/30/choosing-data-types/">Choosing  Data Types</a> and further guidance in reference [1].</p>
<p>I believe there are three reasons why application developers feel that relational schemas are &#8220;inflexible&#8221;:</p>
<ol>
<li>A reliance on NULL semantics to make things &#8220;magically work,&#8221; when in reality, it just makes queries succeed that should fail. See my previous posts: <a title="None, nil, Nothing, undef, NA, and SQL NULL" href="http://thoughts.j-davis.com/2008/08/13/none-nil-nothing-undef-na-and-sql-null/">None, nil, Nothing, undef, NA, and SQL NULL</a> and <a title="What is the deal with NULLs?" href="http://thoughts.j-davis.com/2009/08/02/what-is-the-deal-with-nulls/">What is the deal with NULLs?</a>.</li>
<li>The SQL database industry has avoided interesting types, like <a title="HSTORE" href="http://www.postgresql.org/docs/8.4/static/hstore.html">HSTORE</a>, for a long time. See my previous post: <a title="Choosing Data Types" href="http://thoughts.j-davis.com/2009/09/30/choosing-data-types/">Choosing Data Types</a>.</li>
<li>ORMs make a fundamental false equivalence between an object attribute and a table column. There is a relationship between the two, of course; but they are simply not the same thing. This is a direct consequence of &#8220;The First Great Blunder&#8221;[2].</li>
</ol>
<p><strong>EDIT: </strong>I found a more concise way to express my fundamental point &#8212; During the early stages of application development, we only vaguely understand our data. The most important rule of database design is that the database should represent reality, not what we wish reality was like. Therefore, a database should be able to express that vagueness, and later be made more precise when we understand our data better. None of this should be read to imply that constraints are less important or that we need not understand our data. These ideas mostly apply only at very early stages of development, and even then, prudent use of constraints often makes that development much faster.</p>
<p>[1] Date, C.J.; Darwen, Hugh (2007). <em>Databases, Types, and the Relational Model</em>. pp. 377-380 (Appendix B, &#8220;A Design Dilemma&#8221;).</p>
<p>[2] Date, C.J. (2000). <em>An Introduction To Database Systems</em>, p.  865.</p>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2010/05/06/flexible-schemas-and-postgresql/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Temporal PostgreSQL Roadmap</title>
		<link>http://thoughts.j-davis.com/2010/03/09/temporal-postgresql-roadmap/</link>
		<comments>http://thoughts.j-davis.com/2010/03/09/temporal-postgresql-roadmap/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 04:49:06 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Temporal]]></category>

		<guid isPermaLink="false">http://thoughts.j-davis.com/?p=254</guid>
		<description><![CDATA[Why are temporal extensions in PostgreSQL important? Quite simply, managing time data is one of the most common requirements, and current general-purpose database systems don&#8217;t provide us with the basic tools to do it. Every general-purpose DBMS falls short both in terms of usability and performance when trying to manage temporal data. What is already [...]]]></description>
			<content:encoded><![CDATA[<p>Why are temporal extensions in PostgreSQL important? Quite simply, managing time data is one of the most common requirements, and current general-purpose database systems don&#8217;t provide us with the basic tools to do it. Every general-purpose DBMS falls short both in terms of usability and performance when trying to manage temporal data.</p>
<p>What is already done?</p>
<p><span id="more-254"></span></p>
<ul>
<li><a href="http://pgfoundry.org/projects/temporal">PERIOD data type</a>, which can represent anchored intervals of time; that is, a chunk of time with a definite beginning and a definite end (in contrast to a SQL INTERVAL, which is not anchored to any specific beginning or end time).
<ul>
<li>Critical for usability because it acts as a <em>set</em> of time, so you can easily test for containment and other operations without using awkward constructs like BETWEEN or lots of comparisons (and keeping track of inclusivity/exclusivity of boundary points).</li>
<li>Critical for performance because you can index the values for efficient &#8220;contains&#8221; and &#8220;overlaps&#8221; queries (among others).</li>
</ul>
</li>
</ul>
<ul>
<li>Temporal Keys (called Exclusion Constraints, and will be available in the next release of PostgreSQL, 9.0), which can enforce the constraint that no two periods of time (usually for a given resource, like a person) overlap. See the <a href="http://developer.postgresql.org/pgdocs/postgres/sql-createtable.html">documentation</a> (look for the word &#8220;EXCLUDE&#8221;), and see my previous articles (<a href="../2009/11/01/temporal-keys-part-1/">part 1</a> and <a href="../2009/11/08/temporal-keys-part-2/">part 2</a>) on the subject.
<ul>
<li>Critical for usability to avoid procedural, error-prone hacks to enforce the constraint with triggers or by splitting time into big chunks.</li>
<li>Critical for performance because it performs comparably to a UNIQUE index, unlike the other procedural hacks which are generally too slow to use for most real systems.</li>
</ul>
</li>
</ul>
<p>What needs to be done?</p>
<ul>
<li>Range Types &#8212; Aside from PERIOD, which is based on TIMESTAMPTZ, it would also be useful to have very similar types based on, for example, DATE. It doesn&#8217;t stop there, so the natural conclusion is to generalize PERIOD into &#8220;range types&#8221; which could be based on almost any subtype.</li>
<li>Range Keys, Foreign Range Keys &#8212; If Range Types are known to the Postgres engine, that means that we can have syntactic sugar for range keys (like temporal keys, except for any range type), etc., that would internally use Exclusion Constraints.</li>
<li>Range Join &#8212; If Range Types are known to the Postgres engine, there could be syntactic sugar for a &#8220;range join,&#8221; that is, a join based on &#8220;overlaps&#8221; rather than &#8220;equals&#8221;. More importantly, there could be a new join type, a Range Merge Join, that could perform this join efficiently (without a Range Merge Join, a range join would always be a nested loop join).</li>
<li>Simple table logs &#8212; The ability to easily create an effective &#8220;audit log&#8221; or similar trigger-based table log, that can record changes and be efficiently queried for historical state or state changes.</li>
</ul>
<p>I&#8217;ll be speaking on this subject (specifically, the new Exclusion Constraints feature) in the upcoming <a href="http://postgresqlconference.org">PostgreSQL Conference EAST 2010</a> (my <a href="http://postgresqlconference.org/2010/east/talks/not_just_unique_exclusion_constraints">talk description</a>) in Philadelphia later this month and <a href="http://pgcon.org">PGCon 2010</a> (my <a href="http://www.pgcon.org/2010/schedule/events/201.en.html">talk description</a>) in Ottawa this May. In the past, these conferences and others have been a great place to get ideas and help me move the temporal features forward.</p>
<p>The existing features have been picking up a little steam lately. The <a href="http://lists.pgfoundry.org/pipermail/temporal-general/">temporal-general mailing list</a> has some traffic now &#8212; fairly low, but enough that others contribute to the discussions, which is a great start. I&#8217;ve also received some great feedback from a number of people, including the folks at <a href="http://pgexperts.com">PGX</a>. There&#8217;s still a ways to go before we have all the features we want, but progress is being made.</p>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2010/03/09/temporal-postgresql-roadmap/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Scalability and the Relational Model</title>
		<link>http://thoughts.j-davis.com/2010/03/07/scalability-and-the-relational-model/</link>
		<comments>http://thoughts.j-davis.com/2010/03/07/scalability-and-the-relational-model/#comments</comments>
		<pubDate>Sun, 07 Mar 2010 21:37:24 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://thoughts.j-davis.com/?p=242</guid>
		<description><![CDATA[The relational model is just a way to represent reality. It happens to have some very useful properties, such as closure over many useful operations &#8212; but it&#8217;s a purely logical model of reality. You can implement relational operations using hash joins, MapReduce, or pen and paper. So, right away, it&#8217;s meaningless to talk about [...]]]></description>
			<content:encoded><![CDATA[<p>The relational model is just a way to represent reality. It happens to have some very useful properties, such as closure over many useful operations &#8212; but it&#8217;s a purely logical model of reality. You can implement relational operations using hash joins, MapReduce, or pen and paper.</p>
<p>So, right away, it&#8217;s meaningless to talk about the scalability of the relational model. Given a particular question, it might be difficult to break it down into bite-sized pieces and distribute it to N worker nodes. But going with MapReduce doesn&#8217;t solve that scalability problem &#8212; it just means that you will have a hard time defining a useful map or reduce operation, or you will have to change the question into something easier to answer.</p>
<p><span id="more-242"></span>There may exist scalability problems in:</p>
<ul>
<li>SQL, which defines requirements outside the scope of the relational model, such as ACID properties and transactional semantics.</li>
<li>Traditional architectures and implementations of SQL, such as the &#8220;table is a file&#8221; equivalence, lack of sophisticated types, etc.</li>
<li>Particular implementations of SQL &#8212; e.g. &#8220;MySQL can&#8217;t do it, so the relational model doesn&#8217;t scale&#8221;.</li>
</ul>
<p>Why are these distinctions important? As with many debates, <a title="Terminology Confusion" href="http://thoughts.j-davis.com/2007/12/11/terminology-confusion/">terminology confusion</a> is at the core, and prevents us from dealing with the problems directly. If SQL is defined in a way that causes scalability problems, we need to identify precisely those requirements that cause a problem, so that we can proceed forward without losing all that has been gained. If the traditional architectures are not suitable for some important use-cases, they need to be adapted. If some particular implementations are not suitable, developers need to switch or demand that it be made competitive.</p>
<p>The NoSQL movement (or at least the hype surrounding it) is far too disorganized to make real progress. Usually, incremental progress is best; and sometimes a fresh start is best, after drawing on years of lessons learned. But it&#8217;s never a good idea to start over with complete disregard for the past. For instance, an <a href="http://about.digg.com/blog/looking-future-cassandra">article from Digg</a> starts off great:</p>
<blockquote><p>The fundamental problem is endemic to the relational database mindset, which places the burden of computation on reads rather than writes.</p></blockquote>
<p>That&#8217;s good because he blames it on the <em>mindset</em> not the <em>model</em>,<em> </em>and then identifies a specific problem. But then the article completely falls flat:</p>
<blockquote><p>Computing the intersection with a JOIN is much too slow in MySQL, so we have to do it in PHP.</p></blockquote>
<p>A join is faster in PHP than MySQL? Why bother even discussing SQL versus NoSQL if your particular implementation of SQL &#8212; MySQL &#8212; can&#8217;t even do a hash join, the exact operation that you need? Particularly when almost every other implementation can (including PostgreSQL)? That kind of reasoning won&#8217;t lead to solutions.</p>
<p>So, where do we go from here?</p>
<ol>
<li>Separate the SQL model from the other requirements (some of which may limit scalability) when discussing improvements.</li>
<li>Improve the SQL model (my readers know that I&#8217;ve criticized SQL&#8217;s logical problems many times in the past).</li>
<li>Improve the implementations of SQL, particularly how tables are physically stored.</li>
<li>If you&#8217;re particularly ambitious, come up with a relational alternative to SQL that takes into account what&#8217;s been learned after decades of SQL and can become the next general-purpose DBMS language.</li>
</ol>
<p>EDIT 2010-03-09: I should have cited Josh Berkus&#8217;s talk on <a href="http://www.pgexperts.com/document.html?id=40">Relational vs. Non-Relational</a> (complete list of <a href="http://www.pgexperts.com/presentations.html">PGX talks</a>), which was part of the inspiration for this post.<a href="http://www.pgexperts.com/document.html?id=40"><br />
</a></p>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2010/03/07/scalability-and-the-relational-model/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Temporal Keys, Part 2</title>
		<link>http://thoughts.j-davis.com/2009/11/08/temporal-keys-part-2/</link>
		<comments>http://thoughts.j-davis.com/2009/11/08/temporal-keys-part-2/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 05:48:37 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Temporal]]></category>

		<guid isPermaLink="false">http://thoughts.j-davis.com/?p=180</guid>
		<description><![CDATA[In the last article, I argued that: A schedule conflict is a typical business problem. The later you try to resolve a schedule conflict, the more costly it is to resolve. In particular, there is a big jump in the cost the moment after conflicting data is recorded. Therefore, it&#8217;s best for the DBMS itself [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a title="Temporal Keys, Part 1" href="http://thoughts.j-davis.com/2009/11/01/temporal-keys-part-1/">last article</a>, I argued that:</p>
<ul>
<li>A schedule conflict is a typical business problem.</li>
<li>The later you try to resolve a schedule conflict, the more costly it is to resolve.</li>
<li>In particular, there is a big jump in the cost the moment after conflicting data is recorded.</li>
<li>Therefore, it&#8217;s best for the DBMS itself to enforce the constraint, because only the DBMS can avoid the conflict effectively before the conflict is recorded.</li>
</ul>
<p>Then, I opened up a discussion to see how people are dealing with these schedule conflicts. In the comments I received at the end of the article, as well as other anecdotes from conferences, user groups, mailing lists, and my own experience, the solutions fall into a few categories:</p>
<p><span id="more-180"></span></p>
<ul>
<li>The rate of conflicts is so low that the costs are not important. For instance, you may make 0.1% of your customers unhappy, and need to refund them, but perhaps that&#8217;s a cost you&#8217;re willing to pay.</li>
<li>The application receives so few requests that performance is not an object, and serialization of all requests is a viable option. The serialization is done using big locks and a read-check-write cycle. Even if performance is not an object, these applications sometimes run into maintenance problems or unexpected outages because of the big locks required.</li>
<li>You can break the time slices into manageable chunks, e.g. one day chunks aligned at midnight. This kind of solution is highly specific to the business, reduces the flexibility of the business, and often requires a substantial amount of custom, error-prone procedural code.</li>
<li>Complex procedural code: usually a mix of application code, functions in the DBMS, row-level locking, static data in tables that only exists for the purposes of row-level locks, etc. This kind of solution is generally very specific to the application and the business, requires lots of very error-prone custom procedural code, is difficult to adequately test, and it&#8217;s hard to understand what&#8217;s going on in the system at any given time. Hunting down sporadic performance problems would be a nightmare.</li>
</ul>
<p>Those solutions just aren&#8217;t good enough. We use relational database systems because they are smart, declarative, generally useful for many problems, and maintainable (Note: these principles contrast with <a href="http://en.wikipedia.org/wiki/NoSQL">NoSQL</a>, which is moving in the opposite direction &#8212; more on that in another article).</p>
<p><em>[UPDATE: The following project has been committed for the next release of PostgreSQL; the feature is now called "Exclusion Constraints"; and the new version of PostgreSQL will be called 9.0 (not 8.5). See the <a href="http://developer.postgresql.org/pgdocs/postgres/sql-createtable.html">documentation</a> under the heading "EXCLUDE".]</em></p>
<p>The project that I&#8217;ve been working on for PostgreSQL 8.5 is called &#8220;<a href="https://commitfest.postgresql.org/action/patch_view?id=199">Operator Exclusion Constraints</a>&#8220;. These are a new type of constraint that most closely resembles the <code>UNIQUE</code> constraint, because one tuple can preclude the existence of other tuples. With a <code>UNIQUE</code> constraint on attribute <code>A</code> of a table with attributes <code>(A, B, C)</code>, the existence of the tuple <code>(5, 6, 7)</code> precludes the existence of any tuple <code>(5, _, _)</code> in that table at the same time. This is different from a foreign key, which <em>requires</em> the existence of a tuple in another table; and different from a <code>CHECK</code> constraint which rejects tuples independently from any other tuple in any table (and the same goes for NOT NULL).</p>
<p>The same semantics as a <code>UNIQUE</code> constraint can be easily specified as an Operator Exclusion Constraint, with a minor performance penalty at insert time (one additional index search, usually only touching pages that are already in cache). Exclusion constraints are more general than <code>UNIQUE</code>, however. For instance, with a complex type such as <a href="http://www.postgresql.org/docs/8.4/static/datatype-geometric.html#AEN6211">CIRCLE</a>, you can specify that no two circles in a table overlap &#8212; which is a constraint that is impossible to specify otherwise (without resorting to the poor solutions mentioned above<a title="Temporal Keys, Part 1" href="../2009/11/01/temporal-keys-part-1/"></a>).</p>
<p>This applies to temporal keys very nicely. First, get the <a href="http://pgfoundry.org/projects/temporal">PERIOD data type</a>, which allows you a better way to work with periods of time (sets of time, really), rather than points in time. Second, you need to install the <a href="http://www.postgresql.org/docs/8.4/static/btree-gist.html">btree_gist</a> contrib module. Then, use an exclusion constraint like so:</p>
<p><em>[UPDATE 2010-03-09: Syntax updated to reflect the version of this project committed for PostgreSQL 9.0. ]</em></p>
<pre>CREATE TABLE room_reservation
(
  name   TEXT,
  room   TEXT,
  during PERIOD,
  EXCLUDE USING gist (room WITH =, during WITH &amp;&amp;)
);</pre>
<p>That will prevent two reservations on the same room from overlapping. There are a few pieces to this that require explanation:</p>
<ul>
<li><code>&amp;&amp;</code> is the &#8220;overlaps&#8221; operator for the <code>PERIOD</code> data type.</li>
<li><code>USING gist</code> tells PostgreSQL what kind of index to create to enforce this constraint. The operators must map to search strategies for this index method, and searching for overlapping periods requires a GiST index.</li>
<li>Because we are using GiST, we need GiST support for equality searches for the <code>TEXT</code> data type, which is the reason we need the btree_gist contrib module.</li>
<li>Conflicts will only occur if two tuples have equal room numbers, <em>and</em> overlapping periods of time for the reservation.</li>
</ul>
<p>This solution:</p>
<ul>
<li>Performs well under light and heavy contention. Not quite as well as a UNIQUE constraint, but much better than the alternatives, and without the surprises you might get from using big locks. Note that the constraint <em>will </em>be enforced at some point, so ignoring the problem is not a high-performance alternative (interpersonal communication has higher latency than a computer).</li>
<li>Is declarative. The implementation shows through a little bit &#8212; the user will know that an index is being used, for instance &#8212; but it&#8217;s a relatively simple declaration. As a consequence, it&#8217;s not very error-prone from the schema designer&#8217;s standpoint.</li>
<li>Is not specific to the business. You don&#8217;t have to decide on an appropriate time slice (e.g. one hour, one day, etc.); you don&#8217;t have to try to partition locks in creative ways; you don&#8217;t have to write procedural code (in the database system or application); and you don&#8217;t have to come up with interesting ways to detect a conflict or notify the user.</li>
</ul>
<p>Temporal keys are just one part of the support required for effective temporal data management inside the DBMS. However, it&#8217;s one of the most important pieces that requires support from the core engine, and cannot be implemented as a module.</p>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2009/11/08/temporal-keys-part-2/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>PostgreSQL WEST and Temporal Databases</title>
		<link>http://thoughts.j-davis.com/2009/10/12/postgresql-west-and-temporal-databases/</link>
		<comments>http://thoughts.j-davis.com/2009/10/12/postgresql-west-and-temporal-databases/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 05:09:57 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Temporal]]></category>

		<guid isPermaLink="false">http://thoughts.j-davis.com/?p=152</guid>
		<description><![CDATA[I&#8217;ve been interested in temporal data and relational databases for quite some time. There are going to be at least two people talking about temporal data at PostgreSQL WEST in Seattle: Scott Bailey and me. See the talk descriptions. In the past, I&#8217;ve worked on a temporal extension to PostgreSQL that implements the PERIOD data [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been interested in temporal data and relational databases for quite some time. There are going to be at least two people talking about temporal data at <a title="PG WEST" href="http://postgresqlconference.org">PostgreSQL WEST</a> in Seattle: <a href="http://scottrbailey.wordpress.com/">Scott Bailey</a> and me. See the <a href="http://postgresqlconference.org/2009/west/talks">talk descriptions</a>.</p>
<p>In the past, I&#8217;ve worked on a <a title="Temporal PostgreSQL" href="http://pgfoundry.org/projects/temporal">temporal extension</a> to PostgreSQL that implements the <code>PERIOD</code> data type. This is a data type that offers both a definite beginning and a definite end time, which is important for describing things that happen over a period of time, rather than instantaneously. Trying to use separate attributes for &#8220;start&#8221; and &#8220;end&#8221; is bad for a number of reasons, and will certainly be addressed in a subsequent blog entry. For now, I&#8217;ll just say that I believe the <code>PERIOD</code> data type is fundamentally important for handling all kinds of time data, which I believe is a common problem.</p>
<p>At WEST, I&#8217;ll be presenting my progress on <em>temporal keys</em>. Temporal keys are used to prevent overlapping periods of time &#8212; a schedule conflict &#8212; by using an index and following the same concurrent behavior as <code>UNIQUE</code> with minimal performance cost (one extra index search, to be precise).</p>
<p>Temporal keys cannot be expressed in PostgreSQL 8.4, unless you resort to triggers and a full table lock (ouch!). So, additional backend support is required. This is accomplished in my patch for <a title="Operator Exclusion Constraints GIT repo" href="http://git.postgresql.org/gitweb?p=users/jdavis/postgres.git;a=shortlog;h=refs/heads/operator-exclusion-constraints">operator exclusion constraints</a>, which are a more general way of using arbitrary operators and index searches to enforce a constraint. I plan to do what&#8217;s required for the patch to be accepted in PostgreSQL 8.5.</p>
<p>Temporal modeling is a common problem. It seems like almost every PostgreSQL conference has had at least one talk on the matter, so we know there is some demand for improvement. If you&#8217;re interested, I hope you come to WEST and chat with Scott or I, and let&#8217;s see if we can come up with some real solutions.</p>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2009/10/12/postgresql-west-and-temporal-databases/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>What is the deal with NULLs?</title>
		<link>http://thoughts.j-davis.com/2009/08/02/what-is-the-deal-with-nulls/</link>
		<comments>http://thoughts.j-davis.com/2009/08/02/what-is-the-deal-with-nulls/#comments</comments>
		<pubDate>Sun, 02 Aug 2009 22:40:23 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[PostgreSQL]]></category>

		<guid isPermaLink="false">http://davisjeff.wordpress.com/?p=4</guid>
		<description><![CDATA[A recent thread on pgsql-hackers warrants some more extensive discussion. In the past, I&#8217;ve criticized NULL semantics, but in this post I&#8217;d just like to explain some corner cases that I think you&#8217;ll find interesting, and try to straighten out some myths and misconceptions. First off, I&#8217;m strictly discussing SQL NULL here. SQL NULL is [...]]]></description>
			<content:encoded><![CDATA[<p>A recent <a title="recent thread on pgsql-hackers" href="http://archives.postgresql.org/pgsql-hackers/2009-07/msg01518.php">thread on pgsql-hackers</a> warrants some more extensive discussion. In the past, I&#8217;ve criticized NULL semantics, but in this post I&#8217;d just like to explain some corner cases that I think you&#8217;ll find interesting, and try to straighten out some myths and misconceptions.</p>
<p>First off, I&#8217;m strictly discussing SQL NULL here. SQL NULL is peculiar in a number of ways, and the general excuse for this is that there is a need to represent &#8220;missing information&#8221; &#8212; which may be true. But there are lots of ways to represent missing information, as I pointed out <a title="None, nil, Nothing, undef, NA, and SQL NULL" href="http://thoughts.j-davis.com/2008/08/13/none-nil-nothing-undef-na-and-sql-null/">in a previous post</a>, and SQL&#8217;s approach to missing information is, well, &#8220;unique&#8221;.</p>
<p><span id="more-4"></span></p>
<ul>
<li>&#8220;NULL is not a value&#8221; &#8212; If you hear this one, beware: it&#8217;s in direct contradiction to the SQL standard, which uses the phrase &#8220;null value&#8221; dozens of times. It&#8217;s hard to imagine that NULL is not any kind of value at all; because it&#8217;s routinely passed to functions and operators, predicates can evaluate to NULL, and SQL uses a kind of three-<strong>valued</strong> logic (3VL) in some contexts. The phrase &#8220;NULL is not a value&#8221; also raises the question: &#8220;what is it, then?&#8221;.</li>
<li>NULL means &#8220;unknown&#8221; (i.e. the third truth value) &#8212; This doesn&#8217;t hold up either. SUM of no tuples returns NULL, but clearly the SUM of no tuples is not unknown! SQL will happily generate NULLs from aggregates or outer joins without any NULLs at all in the database. Do you not know something you did know before, or do you now know that you don&#8217;t know something that you didn&#8217;t know you didn&#8217;t know before? Also, if NULL means &#8220;unknown&#8221;, how do you differentiate a boolean field for which you do not know the value, and a boolean field for which you do know the value, and it happens to be &#8220;unknown&#8221; (perhaps this is why boolean columns are a PostgreSQL extension and not part of the core SQL standard)?</li>
<li>&#8220;NULL is false-like&#8221; &#8212; Don&#8217;t think of NULL as false-like, or &#8220;more false than true&#8221;. It&#8217;s a tempting rule of thumb, but it&#8217;s misleading. For instance, in a WHERE clause, a NULL predicate is treated like FALSE. However, in a constraint (like a <code>CHECK</code> constraint), NULL is treated like TRUE. Perhaps most importantly, when in a 3VL context (like a boolean expression), this misconception leads to problems when you try to invert the logic, e.g., use <code>NOT</code>.</li>
<li>&#8220;Oh, that makes sense&#8221; &#8212; When you see individual behaviors of NULL, they look systematic, and your brain quickly sees a pattern and extrapolates what might happen in other situations. Often, that extrapolation is wrong, because NULL semantics are a mix of behaviors. I think the best way to think about NULL is as a Frankenstein monster of several philosophies and systems stitched together by a series of special cases.</li>
<li><code>p OR NOT p</code> &#8212; Everyone should know that this is not always true in SQL. But most people tend to reason assuming that this is always true, so you have to be very careful, and work against your intuition very deliberately, in order to form a correct SQL query.</li>
<li>SUM() versus + (addition) &#8212; SUM is not repeated addition. SUM of <code>1</code> and <code>NULL</code> is <code>1</code>, but <code>1 + NULL</code> is NULL.</li>
<li>Aggregates ignore NULLs &#8212; According to the standard, aggregates are supposed to ignore NULLs, because the information is missing. But why is it OK to ignore the missing information in an aggregate, but not, say, with the + operator? Is it really OK to just ignore it?</li>
<li>Aggregates return NULL &#8212; According to the standard, aggregates are supposed to return NULL when they have no non-NULL input. Just because you don&#8217;t have any input tuples, does that really mean that the result is undefined, missing, or unknown? It&#8217;s certainly not unknown! What about SUM over zero tuples, wouldn&#8217;t the most useful result be zero?</li>
<li>SQL breaks its own rules &#8212; The aforementioned aggregate rules don&#8217;t work very well for <code>COUNT()</code>, the simplest of all aggregates. So, they have two versions of count: <code>COUNT(*)</code> breaks the &#8220;aggregates ignore nulls&#8221; rule and the &#8220;aggregates return null&#8221; rule, and COUNT(x) only breaks the latter. But wait! There&#8217;s more: <code>ARRAY_AGG()</code> breaks the former but not the latter. But no exception is made for SUM &#8212; it still returns NULL when there are no input tuples.</li>
<li>NULLs appear even when you have complete information &#8212; Because of OUTER JOIN and aggregates, NULLs can appear even when you don&#8217;t have any NULLs in your database! As a thought experiment, try to reconcile this fact with the various &#8220;definitions&#8221; of NULL.</li>
<li><code>WHERE NOT IN (SELECT ...)</code> &#8212; This one gets everyone at one point or another. If the subselect produces any NULLs, then NOT IN can only evaluate to FALSE or NULL, meaning you get no tuples. Because it&#8217;s in a WHERE clause, it will return no results. You are less likely to have a bunch of NULLs in your data while testing, so chances are everything will work great until you get into production.</li>
<li><code>x &gt;= 10 or x &lt;= 10</code> &#8212; Not a tautology in SQL.</li>
<li><code>x IS NULL AND x IS DISTINCT FROM NULL</code> &#8212; You probably don&#8217;t know this, but this expression can evaluate to TRUE! That is, if x = ROW(NULL).</li>
<li><code>NOT x IS NULL</code> is not the same as <code>x IS NOT NULL</code> &#8212; If <code>x</code> is <code>ROW(1,NULL)</code>, then the former will evaluate to TRUE, and the latter will evaluate to FALSE. Enjoy.</li>
<li><code>NOT x IS NULL AND NOT x IS NOT NULL</code> &#8212; Want to know if you have a value like <code>ROW(1, NULL)</code>? To distinguish it from NULL and also from values like <code>ROW(1,1)</code> and <code>ROW(NULL,NULL)</code>, this expression might help you.</li>
<li>NULLs can exist inside some things, but not others &#8212; If you concatenate: <code>firstname || mi || lastname</code>, and &#8220;mi&#8221; happens to be null, the entire result will be null. So strings cannot contain a NULL, but as we see above, a record can.</li>
</ul>
<p>I believe the above shows, beyond a reasonable doubt, that NULL semantics are unintuitive, and if viewed according to most of the &#8220;standard explanations,&#8221; highly inconsistent. This may seem minor; that is, if you&#8217;re writing SQL you can overcome these things with training. But it is not minor, because NULL semantics are designed to make you <em>think</em> you understand them, and <em>think</em> that the semantics are intuitive, and <em>think</em> that it&#8217;s part of some ingenious consistent system for managing missing information. But none of those things are true.</p>
<p>I have seen lots of discussions about NULL in various forums and mailing lists. Many of the participants are obviously intelligent and experienced, and yet make bold statements that are, quite simply, false. I&#8217;m writing this article to make two important points:</p>
<ol>
<li>There is a good case to be made that NULL semantics are very counterproductive; as opposed to a simple &#8220;error early&#8221; system that forces you to write queries that explicitly account for missing information (e.g. with <code>COALESCE</code>). &#8220;Error early&#8221; is a more mainstream approach, similar to null pointers in java or None in python. If you want compile-time checking, you can use a construct like Maybe in haskell. SQL attempts to pass along the problem, hoping the next operator will turn ignorance into knowledge &#8212; but it does not appear that anyone thought through this idea, quite frankly.</li>
<li>You should not attempt to apply your intellect to NULL, it will lead you in the wrong direction. If you need to understand it, understand it, but always treat it with skepticism. Test the queries, read the standard, do what you need to do, but do <strong>not<em> </em></strong>attempt to extrapolate.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2009/08/02/what-is-the-deal-with-nulls/feed/</wfw:commentRss>
		<slash:comments>45</slash:comments>
		</item>
		<item>
		<title>ruby-pg is now the official postgres ruby gem</title>
		<link>http://thoughts.j-davis.com/2007/12/14/ruby-pg-is-now-the-official-postgres-ruby-gem/</link>
		<comments>http://thoughts.j-davis.com/2007/12/14/ruby-pg-is-now-the-official-postgres-ruby-gem/#comments</comments>
		<pubDate>Fri, 14 Dec 2007 18:00:10 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://davisjeff.wordpress.com/?p=18</guid>
		<description><![CDATA[ruby-pg is now the official rubyforge project for the &#8220;postgres&#8221; ruby gem. See the project here: http://www.rubyforge.org/projects/ruby-pg or install the gem directly: # gem install &#8211;remote postgres The previous project has gone unmaintained for a long time, which lead to the fork. This gem includes some important fixes, most notably the ability to compile against [...]]]></description>
			<content:encoded><![CDATA[<div>ruby-pg is now the official rubyforge project for the &#8220;postgres&#8221; ruby<br />
gem. See the project here:</p>
<p><a href="http://www.rubyforge.org/projects/ruby-pg">http://www.rubyforge.org/projects/ruby-pg</a></p>
<p>or install the gem directly:</p>
<p># gem install &#8211;remote postgres</p>
<p><span id="more-18"></span></p>
<p>The previous project has gone unmaintained for a long time, which lead<br />
to the fork.</p>
<p>This gem includes some important fixes, most notably the ability to<br />
compile against PostgreSQL 8.3.</p>
<div>The gem contains two modules:</p>
<ul>
<li>&#8216;postgres&#8217; &#8212; require this module as before, you can use it without<br />
making any changes to your application. This is essentially just a fork<br />
from version 0.7.1.2006.04.06, but contains some important fixes,<br />
including the ability to build against 8.3.</li>
<li>&#8216;pg&#8217; &#8212; a new interface, designed to offer every feature available in<br />
libpq to Ruby, with a better API. This module is simpler, cleaner, and<br />
more portable. It is still unstable, so test before using.</li>
</ul>
<p>PostgreSQL+Ruby users: please test and report any problems. I&#8217;d like to<br />
make sure this is as stable as possible, and builds on all necessary<br />
platforms.</p></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2007/12/14/ruby-pg-is-now-the-official-postgres-ruby-gem/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>On ORMs and &quot;Impedence Mismatch&quot;</title>
		<link>http://thoughts.j-davis.com/2007/12/03/on-orms-and-impedence-mismatch/</link>
		<comments>http://thoughts.j-davis.com/2007/12/03/on-orms-and-impedence-mismatch/#comments</comments>
		<pubDate>Mon, 03 Dec 2007 18:00:56 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[PostgreSQL]]></category>

		<guid isPermaLink="false">http://davisjeff.wordpress.com/?p=6</guid>
		<description><![CDATA[The solution ORMs provide is to &#8220;map&#8221; an object class, which is a type (or domain), onto a table, which is a relation variable (a.k.a. relvar). This supposedly abstracts away an &#8220;impedance mismatch&#8221; between the two. ORMs are already off to a bad start, mapping a type to a variable, but I&#8217;ll continue. The real [...]]]></description>
			<content:encoded><![CDATA[<p>The solution ORMs provide is to &#8220;map&#8221; an object class, which is a type (or domain), onto a table, which is a relation variable (a.k.a. relvar). This supposedly abstracts away an &#8220;impedance mismatch&#8221; between the two. ORMs are already off to a bad start, mapping a type to a variable, but I&#8217;ll continue.</p>
<p>The real impedance mismatch is a set of very fundamental differences between application data and data in a well-designed relational database.</p>
<p><span id="more-6"></span></p>
<p>Application data:</p>
<ul>
<li> is ephemeral in nature (that is, temporary)</li>
<li> is subject to changes in structure between revisions of the same application</li>
<li> is subject to changes in semantics (meaning) between revisions of the same application</li>
<li> the meaning is highly context-sensitive</li>
<li> the data is highly dependent on physical structure</li>
<li> not all of the data that has been processed by the application is held at once, meaning that contradictions are often impossible to detect (for instance, something as simple as a duplicate serial number).</li>
</ul>
<p>While data in a well-designed database:</p>
<ul>
<li> has a definite predicate that maps the data to <strong>real world facts independent of the application</strong></li>
<li> these facts are kept as long as the fact is still believed to be true and relevant</li>
<li> these facts are context-insensitive</li>
<li> these facts are independent of any physical structure or implementation</li>
<li> is held all at once, allowing detection of contradictions through complex logical relationships, enforced by declarative constraints</li>
</ul>
<div>These differences are, loosely speaking, the same as the differences between &#8220;save&#8221; and &#8220;commit&#8221;.</p>
<p>Some people like to think that an ORM is something that should just be plugged in to add &#8220;persistence&#8221; without requiring database design. This idea views the difference between application data and relational data as an impedance mismatch that can be overcome with clever code. The entire premise behind that idea is that an RDBMS is a legacy technology, or that the only reason an RDBMS is needed is for performance, reliability, stability, backup procedures, and other services that any DBMS provides.</p>
<p>In reality, the impedance mismatch is the difficulty in mapping application data to facts in the real world. The process of inserting new information into a database is not just the process of making that data persistent; it is the processes of <em>reconciling</em> that new information through <em>automated logical inferences</em> with <em>all the other data in the system</em> and, if a logical contradiction is detected, rejecting the new information with a meaningful error.</p>
<p>Back to ORMs. Why &#8220;map&#8221; the object, and not just store it directly? Modern relational databases support a wide range of types, and also the ability to declare your own types, including sophisticated types (like an object). You can define input and output routines (for transmission to/from the client application), and then all of the operators on that type. There is some duplicity in first defining the object in the application, and then defining it again in the database, but I don&#8217;t think that&#8217;s the only reason.</p>
<p>If you put the entire object into one field, you can see right away that no meaning has been stored. Moreover, you will realize soon after that the implementation of the object has been solidified in the database, and therefore it&#8217;s no longer so easy to change the implementation details of the application. However, when you dump the internals of an object into separate fields in a table, there is the illusion that the meaning of that data has been stored as well, and the illusion that the data is independent of the implementation. This is the same illusion as when an object is serialized as XML: it looks like there&#8217;s meaning there, but there really isn&#8217;t, it&#8217;s just serialized data made from some internal application state with no meaning outside of context.</p>
<p>If you actually take the time to design predicates that have meaning in the real world, and from which inferences can be made when logically combined with other predicates, and then map the application data to real world facts that match those predicates; only then are you free from the implementation details of the specific revision of the specific application that inserted the data, and have enough information that you can make automated inferences from that data.</p>
<p>The point of all this is not that users of ORMs are wrong necessarily, my point is that there is no &#8220;holy grail&#8221; ORM solution that will solve these problems for you. Often, ORMs get in the way of you trying to solve those problems. Recognize the limits of an ORM, and as long as you don&#8217;t sacrifice data integrity, then work within those limits.</p></div>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2007/12/03/on-orms-and-impedence-mismatch/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>
