185 | | |
| 185 | - That could work, yes. How about this: |
| 186 | {{{ |
| 187 | #!python |
| 188 | cursor.execute("UPDATE cache SET generation=generation+1 " |
| 189 | "WHERE key=%s", (key,)) |
| 190 | cursor.execute("SELECT generation FROM cache WHERE key=%s", (key,)) |
| 191 | if not cursor.fetchone(): |
| 192 | cursor.execute("INSERT INTO cache VALUES (%s, %s)", (key, 0)) |
| 193 | }}} |
| 194 | If the row already exists, it is updated, the `SELECT` returns a row and we're done. |
| 195 | If not, the `UPDATE` does nothing except starting a transaction (or we may already be in a transaction), the `SELECT` |
| 196 | doesn't return any rows, and we do the `INSERT` in the same transaction. Doesn't the `UPDATE` even return the number |
| 197 | of altered rows? That would remove the need for a separate `SELECT`. I'm not sure though that the `UPDATE` starts a transaction |
| 198 | if no rows are altered. We may have to use a dummy row that is always updated in addition to the desired row. |