[storm] Update or add pattern with Storm
Jamu Kakar
jkakar at canonical.com
Fri Oct 10 19:25:26 BST 2008
Hi,
Gerdus van Zyl wrote:
> I currently do this:
> store = getStore()
> rcount = store.find(customer,customer.lastname==u"Sparrow").count()
> exists = (rcount > 0)
> print exists
>
> Which is simple as dirt, what code do you use? And why do you say it's
> not efficient?
According to somewhat dated information[1] COUNT can be slow on
PostgreSQL because it does table scans. It hints at improvements in
8.2 that might make the issues explained go away. Nonetheless, I
have heard of people having performance problems with COUNT in the
recent past, so I avoid it unless I actually need the row count. I
primarily use PostgreSQL so I don't know anything about COUNT with
other database backends.
I use ResultSet.any to produce the same result as your code snippet
above, to avoid using COUNT:
exists = bool(store.find(Customer, Customer.last_name == u"Sparrow").any())
To solve the original poster's issue, where one needs to determine
if an object exists and then create or update it, I'd use something
like:
customer = store.find(Customer, Customer.last_name == u"Sparrow").one()
if not customer:
customer = store.add(Customer(u"Jack", u"Sparrow"))
else:
customer.first_name = u"Jack"
customer.last_name = u"Sparrow"
You need to use a query that will only ever return 0 or 1 row when
you use ResultSet.one. If more than 1 row is returned a NotOneError
will be raised.
Thanks,
J.
[1]
http://wiki.postgresql.org/wiki/Introduction_to_VACUUM,_ANALYZE,_EXPLAIN,_and_COUNT
More information about the storm
mailing list