Re: [SQLObject] a simple question and small code changes
SQLObject is a Python ORM.
Brought to you by:
ianbicking,
phd
From: Luke O. <lu...@me...> - 2003-04-03 17:12:21
|
> > How do you normally deal with knowing if a row exists in > the database? > e.g. (looking for person id 12 which doesn't exist in db) > p = Person(12) > p.id will return 12 > p.name throws an error (likewise for other columns) > > Would something along the lines of p.exists() make any > sense? This is something that is missing from SQLObject, IMO. There are two possibilities as I see if for fixed functionality: p = Person(12) still works, and we add p.exists() as a function (functionality already exists in the DBConnection, as it is what makes p.name fail). or p = Person(12) throws an exception (KeyError?) (based on internally calling self.exists()/equivalent). I prefer option two, as I can't come up with a scenario where I want an invalid Person object to be instantiated; it means that everytime I instantiate an object I'll end up calling .exists() anyways. I suppose the downside is for .select(), as there is now an SQL check for every instantiation, when we're pretty confident the objects exist... but it's price I'm willing to pay, especially with caching on. Hmm. Public .exists() functionality should be available too, for situations where SQLObject-based access is used alongside other database access methods, since in these cases an object can become obsolete without SQLObject knowing it (but these situations are not preferrable, so I would rather leave it up to the implementor to deal with this than calling .exists() at every get/update in SQLObject.) Modified code below (an addition to the end of _init(), and exists()). This could alternatively be a function in DBConnection, if we're continuing to move SQL out of SQLObject. def _init(self, id, connection=None): ........ # Stop everything if this doesn't exist. if not self.exists(): raise KeyError, "The object %s by the ID %s does not exist" % (self.__class__.__name__, self.id) def exists(self): q = "SELECT %s FROM %s WHERE %s = %s" % \ (self._idName, self._table, self._idName, self.id) results = self._connection.queryOne(q) return bool(results) Enjoy, - Luke |