# Auto Increment

> Sequential numbers on every database, MongoDB included - isAutoIncrementByAM in the schema, start and step, how the next value is chosen, the Auto Increments page, and what travels with Git.

Source: https://docs.apimaker.dev/v1/docs/features/auto-increment.html

MongoDB has no auto increment column. API Maker gives one to every database : mark a number field with `isAutoIncrementByAM` and every row saved through the schema APIs gets the next number.

| | |
|---|---|
| Schema | `order_no: { __type: EType.number, isAutoIncrementByAM: { start: 1000, step: 5 } }` ; `true` means start `1`, step `1`. |
| Counter | One per field, kept in the internal Redis of API Maker, shared by every server. |
| Page | `Utility → Auto Increments` : every counter of the account, with its last value, which you can edit. |
| Git | The counters of a branch are written to `Auto Increments/auto_increments_<branch>.yml` in the repository. |

## How the next value is chosen

1. The counter of the field is increased by `step`. This is atomic : two servers saving at the same time get two different numbers.
2. When the result is not above `start` (a new counter, or a counter reset below `start`), API Maker reads the highest value the table already has : the next value is that maximum plus `step`, and at least `start`.
3. The value is written in the row. A value sent in the payload is replaced.

| Start | Step | Counter | Highest in table | Next value |
|---|---|---|---|---|
| 1000 | 5 | 1020 | | 1025 |
| 1000 | 5 | none | 1100 | 1105 |
| 1000 | 5 | none | empty table | 1000 |
| 1 | 1 | none | empty table | 1 |

- Rows inserted outside API Maker are picked up the next time the counter starts from scratch ; edit the counter on the Auto Increments page to realign it right away.
- `isAutoGenerateByAM` on the same field wins, and `isAutoIncrementByDB` disables it : let the database count when it can.

## The Auto Increments page

- Lists the counters of the environment : instance, database, table, field path and the last generated value.
- **Edit** sets the last value ; the next row gets it plus `step`. The dialog shows the values the next number will be the maximum of.
- **Delete** removes a counter : the next save reads the highest value of the table again.

## With Git

- A pull writes the counters of the branch into Redis when they are missing there ; a counter which exists on the server is never replaced by the one of Git.
- A new environment therefore starts from the counters of the branch, and a running one keeps its own.

## Related

- [Table schema](https://docs.apimaker.dev/v1/docs/schema/schema.html#5-keys-and-generated-values) · [Git integration](https://docs.apimaker.dev/v1/docs/Git/git.html)
