Domanda

I'm creating a system that involves the reservation of tickets by many users within a short period of time with only a certain number of reservations possible in total. Say 600 tickets available, potentially all being reserved in 3 hour period or less.

Ideally I want to ensure the limit of reservations is not reached so before creating a reservation I am checking whether it's possible to make the reservation against the number of tickets available. Crucially I need to make sure no updates take places between that check and assigning the tickets to a user, to be sure the ticket limit won't be exceeded.

I'm trying to use mysql table write locks to achieve this however am running into problems implementing this within the codeigniter framework. Within the model handling this I've created several functions, one for creating the reservation and others for counting numbers of different types of tickets. The problem is that they don't seem to be sharing the same database sessions as they ticket counting functions are locking up.

The order of execution is

  • run $this->model_name->create_reservation in controller
  • run lock query in model_name->create_reservation
  • call counting method in model_name->create_reservation
  • counting function (which is a method in the model_name class) locks up, presumably because using different database session?

The database library is loaded in the model __construct method with $this->load->database();

Any ideas?

È stato utile?

Soluzione

In mysql, you run these commands on your DB handle before running your queries the tables will auto lock :

begin work;

You then run your queries or have code igniter run your various selects and updates using that db handle.

Then you either

commit;

or

rollback;

Any rows you select from will be locked and can't be read by other processes. If you specifically want the rows to still be readable, you can do:

Select ... IN SHARE MODE

From Mysql docs:

http://dev.mysql.com/doc/refman/5.5/en/select.html

If you use FOR UPDATE with a storage engine that uses page or row locks, rows examined by the query are write-locked until the end of the current transaction. Using LOCK IN SHARE MODE sets a shared lock that permits other transactions to read the examined rows but not to update or delete them. See Section 13.3.9.3, “SELECT ... FOR UPDATE and SELECT ... LOCK IN SHARE MODE Locking Reads”.

Another person said this in comments already, but from the CI docs:

$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
$this->db->trans_complete(); 

trans_start and trans_complete will run those queries for you on your handle...

there is probably a trans_rollback too...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top