Primary Keys and ATK

From Achievo/ATK Wiki

Revision as of 09:56, 11 March 2011 by Bahati (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

ATK Howto: Primary Keys and ATK

Complexity: Easy
Author: Lorna Mitchell

List of other Howto's

When first working with new software, it is sometimes helpful to look directly at the database, and sometimes we want to insert records manually to allow us to work with another part of the system before the data can be added in the usual way. When records are inserted manually to the database, then errors may appear in the ATK interface at a later stage, complaining about a duplicate key.

Tables in ATK do not have auto_increment columns for their primary keys. This is a deliberate design decision to allow the system to be database-independent, since not all database platforms support the auto_increment. Instead the increments are handled as a sequence, with the sequence values stored in db_sequence.


Manually Inserting Data

To manually insert data you should refer to the db_sequence table for the next id to use, then insert your data including the id into the table. If you want to insert multiple rows then go ahead and do this, with new id values for each row. Once you have finished inserting data, go back to the db_sequence table and update it with the next id to use so that ATK can continue to operate on this table.


Using Automatically Incrementing Columns

It is possible to work with automatically incrementing columns and ATK, but there are a few things that need to be changed. When adding the attribute, use the AF_PRIMARY flag rather than AF_AUTOKEY - it is also necessary to remove the AF_OBLIGATORY flag; the result looks something like this:

$attr = &$this->add(new atkAttr("id",AF_PRIMARY|AF_HIDE));
$attr->removeFlag(AF_OBLIGATORY);

When saving the record, a NULL value is sent to allow the database to do its own id insertion, using a function like the one below (assuming your column is called "id"):

 public function initial_values() { 
   return array("id"=>NULL); 
 }

Take care though that if you use NF_EDITAFTERADD or any of the postEdit functionality, this will not work unless you specifically retrieve the value of the inserted record.

Personal tools
Navigation