Modifying the database in db_update / db_insert

C
alling perform_database_insert eventually results in a call to db_insert method of the DisplayClass, and similarly perform_database_update results in a call to db_update. It is up to the developer to do the actual inserts/updates.

Dont forget to check the mode, and do the appropriate action. To help with the actual inserts and updates, use the queries.Update and queries.Insert class. Care should be taken to maintain the integrity of the database. Before doing any updates/inserts, one should lock all the tables, do the changes and then unlock the tables after the changes are made. This makes sure that other users seeing the database dont see it in an inconsistent state. A common misconception is to lock the tables only before the actual change to the database. You should lock the tables before doing any read which preceedes the write, as it is possible that some other process could read and write the database between our read and write (Only god knows the ways in which Operating Systems schedule the process!). Another thing to look out for is exceptions when modifying the database. You need to make sure that the tables are unlocked eventually, even if any exceptions are raised during the process of modifying the database. For eg. if a WebError exception is raised during the process of writing to a table, the control passes to the dispatcher module, and then the tables are not unlocked. After this no other process can read the locked tables, and one will have to restart the server. All this is handled in the following piece of psuedocode:

try:
  1. lock all the tables necessary
  2. read existing data from the table and confirm that this modification will 
     not result in any integrity violations. (Eg. when adding a new course, 
     first check that it is not already there...)
  3. Construct the Update/Insert query.
  4. try:
       execute the update/insert query
     except MySQLdb.Error,e:
       code to catch SQL errors (e is the exception object)
       -- if the code in step 2 is correct this should never be executed.
finally:
   unlock all the tables

The finally clause, ensures that the code following it is always executed irrespective of whether an exception is raised within the try block or not.