164 | | - That's what I tried first, but the error due to the `INSERT` rolled back the whole transaction. I'll have to find a way to do this in a single statement. |
| 164 | - That's what I tried first, but the error due to the `INSERT` rolled back the whole transaction. I'll have to find a way to do this in a single statement. |
| 165 | - Hm right, that can be problematic. So what about this: |
| 166 | {{{ |
| 167 | #!python |
| 168 | cursor.execute("SELECT generation FROM cache WHERE key=%s", |
| 169 | (key,)) |
| 170 | do_update = cursor.fetchone() |
| 171 | if not do_update: |
| 172 | try: |
| 173 | cursor.execute("INSERT INTO cache VALUES (%s, %s)", |
| 174 | (key, 0)) |
| 175 | except Exception: |
| 176 | do_update = True |
| 177 | if do_update: |
| 178 | cursor.execute("UPDATE cache SET generation=generation+1" |
| 179 | "WHERE key=%s", (key,)) |
| 180 | }}} |
| 181 | If we were in a transaction, then I suppose the SELECT/INSERT |
| 182 | sequence can't fail. Conversely, if it fails, then we were |
| 183 | ''not'' in a transaction, and we can follow-up with an UPDATE |
| 184 | to recover from the failed INSERT. |
| 185 | |