I'm a missionary in Japan. The name of my mission agency is WEC International. That's supposedly Worldwide Evangelisation for Christ, but I think I have a better idea about what it stands for...
2007-04-02
ORM In Javascript
Years before people were creaming off about Active Record and Ruby on Rails, we were doing all that in Perl. The general principle behind Active Record is called "object relational mapping", since, predictably, it maps a relational database onto objects in your programming language. There's a chapter of Advanced Perl Programming about this and how it works.
So as you know, recently I've been fiddling a lot with Mozilla extensions, and also Songbee which is now a Mozilla application, and I've wanted them to be database backed. Thankfully, Mozilla apps these days ship with the Storage component, which is an API to SQLite. Fantastic, if you like writing SQL. I don't, and I've really missed the ORM systems I'm used to like Perl's Class::DBI. So I sat down and started writing an ORM in Javascript. Here it is.
With this, in your Mozilla application you can connect to a data source and then associate some classes with database tables:
var storageService = Components.classes["@mozilla.org/storage/service;1"]
.getService(Components.interfaces.mozIStorageService);
var mDBConn = storageService.openDatabase(file);
function Mail () {}; databaseclass(Mail, "mail");
function Attachment () {}; databaseclass(Attachment, "attachment");
function Entity () {}; databaseclass(Entity, "entity");
And with that, you have active records:
var mail = Mail.retrieve(msgid);
if (!mail) mail = Mail.create({ message_id: msgid, message: body });
// ...
mail.last_read((new Date).toUTCString());
// ...
mail.drop();
Currently you have to work out relationships yourself, but that shouldn't be far off once I start actually storing attachments and entities. At least it currently intuits all the field names and the primary key for you.
If you're working with Mozilla applications which you want to be database backed, and you're used to the Object Relational Mapping style of programming, have a look at class-dbi.js.
| « | 2007-04 | » | ||||
|---|---|---|---|---|---|---|
| S | M | T | W | T | F | S |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
| 29 | 30 | |||||
lathos: Heading down to Oookayama. The おおお joke never gets old.





