Skip to content

Instantly share code, notes, and snippets.

@onethirtyfive
Created July 13, 2011 04:42
Show Gist options
  • Save onethirtyfive/1079730 to your computer and use it in GitHub Desktop.
Save onethirtyfive/1079730 to your computer and use it in GitHub Desktop.
How to query this database with DM query language?
Here's the relevant part of the schema, simplified, showing relations:
CREATE TABLE "units" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" VARCHAR(50)
);
CREATE TABLE "champions" (
"unit_id" INTEGER NOT NULL,
"title" VARCHAR(50),
PRIMARY KEY("unit_id")
);
CREATE TABLE "structures" (
"unit_id" INTEGER NOT NULL,
"title" VARCHAR(50),
PRIMARY KEY("unit_id")
);
"champions" and "structures" are both types of "units". This scheme is the inverse of normal polymorphic relationships. In ActiveRecord, units would polymorphically point at each subtype with a "type" column.
So:
class Champion
property :unit_id, Integer, :key => true # not serial
belongs_to :unit
end
class Structure
property :unit_id, Integer, :key => true # not serial
belongs_to :unit
end
The problem is that I have to do an explicit SQL join for the inverse relationship:
# This is nonsensical:
class Unit
has 1, :champion, :structure, or whatever subtype
end
Rather, I need to accomplish a query like this:
SELECT *
FROM units AS u
LEFT OUTER JOIN structures AS s USING (unit_id)
LEFT OUTER JOIN champions AS s USING (unit_id)
[and all the other unit subtypes I add, eventually...]
WHERE u.name = 'Olga';
Is there any way to programmatically accomplish this kind of query without executing SQL in DM?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment