Jump to content

Primary Keys and ATK

From NusaATK
Revision as of 15:54, 9 July 2008 by Lorna (talk | contribs) (Adding notes on primary keys that I gathered working on a recent ATK project)

ATK Howto: Primary Keys and ATK

Complexity: Easy
Author: Lorna Mitchell <lorna@ibuildings.nl>

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. Rather than using the AF_AUTOKEY for the primary key of a node, the flag AF_PRIMARY should be used. You should also make sure that when saving, you send a NULL value 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.