I am attempting to create a special kind of unique
constraint on a table. The database models users, groups and realms. I
am attempting to force usernames to be unique inside of a single realm. I surmised that the check for this should go inside of a mapper extension on before_insert: class UserMapperExtension(MapperExtension): """ An extension to the mapper so that when users are created they are unique inside of their realm. """ def before_insert(self, mapper, connection, instance): print instance.username, instance.password if instance.realm_id: sql = """ SELECT COUNT(*) FROM user WHERE realm_id=%s AND username='%s'""" % (instance.realm_id, instance.username) res = list(connection.execute(sql))[0] if res[0]: raise DuplicateError, "A username '%s' already exists in realm '%s'" % (instance.username, instance.realm.name) This does not work when there are more than 1 users added before a single flush call. It appears that the hook is called for each user. However, no previous SQL for the users has been executed during any before_insert hook call. I can detect a duplicate using after_insert: def after_insert(self, mapper, connection, instance): sql = """ SELECT COUNT(*) FROM user WHERE realm_id=%s AND username='%s'""" % (instance.realm_id, instance.username) count = connection.execute(sql).fetchone()[0] if count > 1: raise DuplicateError, "A username '%s' already exists in realm '%s'" % (instance.username, instance.realm.name) However, this is after the fact and the data is already there. I have a feeling there is an easier way to do this and I am just barking up the wrong tree. |
begin:vcard fn:Jeremy Lowery n:Lowery;Jeremy email;internet:[EMAIL PROTECTED] title:Project Manager tel;work:(256) 390-2417 tel;fax:(205) 421-1747 x-mozilla-html:FALSE version:2.1 end:vcard
------------------------------------------------------------------------- Take Surveys. Earn Cash. Influence the Future of IT Join SourceForge.net's Techsay panel and you'll get the chance to share your opinions on IT & business topics through brief surveys -- and earn cash http://www.techsay.com/default.php?page=join.php&p=sourceforge&CID=DEVDEV
_______________________________________________ Sqlalchemy-users mailing list Sqlalchemy-users@lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/sqlalchemy-users