Supporting Adodb Sequences And Activerecord At The Same Time...

I have an old system (A) made with Prado, which uses adodb as the database access layer, and the new (B) version mostly using Yii’s ActiveRecord. The problem were the sequences, which adodb uses to keep the max id of a table, useful to avoid race conditions when you use master-detail tables, for instance. But with ActiveRecord you get your $model->id primary key set when you $model->save, so the _seq table is not updated. This is no problem if you replace system A with system B, but if you need both versions running in parallel then you’re in troubles. This code, when wisely used in the afterSave of the model, updates the _seq table for that model:


if (Yii::app()->params['COMPAT3']===true && $this->scenario==='insert') {

     	$table = $this->tableName();

     	$sec = get_class($this).'Seq';

     	$db = Yii::app()->db;

     	$sql =<<<EOP

SELECT MAX(id) AS max FROM {$table}

EOP;

     	$cmd = $db->createCommand($sql);

     	$rd = $cmd->query();

     	$rs = $rd->read();

     	if (isset($rs['max'])) {

        	if ($sec::model()->exists()) {

           	$sql = "UPDATE {$table}_seq SET id={$rs['max']}";

        	}

        	else {

           	$sql = "INSERT INTO {$table}_seq (id) VALUES ({$rs['max']})";

        	}

        	$cmd = $db->createCommand($sql);

        	$cmd->execute();

     	}

  	}

You might notice the [font=“Courier New”]Yii::app()->params[‘COMPAT3’]===true[/font] , which is just a flag to indicate if we need to have both versions in parallel.