Next: , Previous: %typedef and %type, Up: Top


11 %auto

This special field allows to include auto-generated fields in our databases. Its usage is:

     %auto: field1 field2 ... fieldN

The list of field names are separated by one or more blank characters. There can be several %auto fields in the same record descriptor, the effective list of auto-generated fields being the union of all the entries.

Auto generated fields are a very useful facility usually providen by database implementations. Consider for example a list of articles in stock in a toys store:

     %rec: Item
     %key: Description
     
     Description: 2cm metal soldier WWII
     Amount: 2111
     
     Description: Flying Helicopter Indoor Maxi
     Amount: 8
     
     ...

It would be natural to identify the items by its description, but it is also error prone: was it “Flying Helicopter Indoor Maxi” or “Flying Helicopter Maxi Indoor”? Was “Helicopter” in lower case or upper case?

It is quite common in databases to use some kind of numeric “Id” to uniquely identify items like those ones. That is because numbers are easy to operate with, and to increase. So we could add a new numeric Id field and use it as the primary key:

     %rec: Item
     %key: Id
     %mandatory: Description
     
     Id: 0
     Description: 2cm metal soldier WWII
     Amount: 2111
     
     Id: 1
     Description: Flying Helicopter Indoor Maxi
     Amount: 8
     
     ...

A problem of this approach is that we must be careful to not assign already used ids when we introduce more articles in the database. Other than its uniqueness, it is not important which number is associated with which article.

To ease the management of those Ids database systems use to provide a facility called “auto-counters”. Auto-counters can be implemented in recfiles using the %auto directive in the record descriptor:

     %rec: Item
     %key: Id
     %type: Id int
     %mandatory: Description
     %auto: Id
     
     Id: 0
     Description: 2cm metal soldier WWII
     Amount: 2111

Next time a new item is introduced in the database, the conforming application will note the %auto, and will create a new Id field for the new record with the bigger unused integer available. In this example, the new record will have an Id of 1. The application can still provide an explicit Id for the new record. In that case the field is not generated automatically.

The concrete effect of the %auto directive depends on the type of the affected field:

Auto generated dates can be used to implement automatic timestamps. Consider for example a “Transfer” record set registering bank transfers. We want to save a timestamp every time a transfer is done, so we include an %auto for the date:

     %rec: Transfer
     %key: Id
     %type: Id int
     %type: Date date
     %auto: Id Date

Note that the auto fields are generated at the beginning of the new records, in the same order they are found in the %auto directives.