[Helma-user] difficult object relational mapping

Joshua Paine joshua at papercrown.org
Thu Mar 6 05:07:23 CET 2008


Maksim Lin for technical support mailling lists wrote:
> function getEventsByRecentChanges() {
> 	var sqlResult =
> helma.Database.getInstance("MyDataSource").query("SELECT ID from ...);
> 	var resultList = [];
> 	for (var i=0; i < sqlResults.length; i++) {
> 		resultList.push( Event.getById(sqlResult.[i].ID) );
> 	}
> 	return resultList;
> }

This is worse than what Breton suggested because it loads every Event in 
the DB into memory all at once. For the original poster I still favor a 
way to use the provided collections feature.

We could improve on your sample code, though, to get something at least 
as fast that only loads the entire list of IDs into memory at once. 
(That's still too much in some cases, but this will work in more cases 
than the sample above.) Also make it generic and act a bit like a 
HopObject collection:

function createOrderedView(hopType,dataSourceName,query) {
   /* query must select ID */
   var rx = /^\s*[Ss][Ee][Ll][Ee][Cc][Tt]\s+(\w+\s+(as\s+)?)?ID,?\s/;
   if(!rx.test(query)) return null;
   var sqlResults = helma.Database.getInstance(dataSourceName)
                    .query(query);
   var pub = ({
     get : function(i) {
       if(!sqlResults[i]) return null;
       return hopType.getById(sqlResults[i].ID);
     },
     size : function() {
       return sqlResults.length;
     },
     list : function() {
       var l = [];
       for(var i = 0; i < sqlResults.length; i++) l[i] = pub.get(i);
     }
   });
   return pub;
}

This code has not been run. Fixing any errors is left as an exercise to 
the reader ;-).


More information about the Helma-user mailing list