# gizmodel/sql/catalog/sequence

Sequences as Oracle and PostgreSQL define them: a step (negative counts down), bounds, and CYCLE, which starts again at the far bound instead of failing. A value handed out is never handed out again, even when its statement or transaction rolls back.

```gizlang
import * as Sequence from "gizmodel/sql/catalog/sequence";
```

## Types

### `Sequence`

```gizlang
type Sequence = { next: i64; step: i64; min: i64; max: i64; cycle: bool; start: i64; }
```

`next`: the value NEXTVAL gives next; `start`: the value RESTART goes back to.

- `next`: `i64`
- `step`: `i64`
- `min`: `i64`
- `max`: `i64`
- `cycle`: `bool`
- `start`: `i64`

### `SeqRef`

```gizlang
type SeqRef = { name: string; op: string; fn: i64; per: i64; }
```

`per`: the NEXTVAL calls of the sequence in each select-list row (PostgreSQL draws each call apart).

- `name`: `string`
- `op`: `string`
- `fn`: `i64`
- `per`: `i64`

### `Draw`

```gizlang
type Draw = { name: string; seq: Sequence; nexts: bool; per: i64; }
```

A sequence a statement draws from, as it was when the statement began; `nexts`: it calls
NEXTVAL.

- `name`: `string`
- `seq`: `M171.Sequence`
- `nexts`: `bool`
- `per`: `i64`

## Functions

### `sequence`

```gizlang
function sequence(step: i64): Sequence
```

The defaults for `step`: ascending from 1, or descending from -1.

Effects: fail.

### `sequenceText`

```gizlang
function sequenceText(q: Sequence): string
```

As stored: "next step min max cycle start"; a stored text of one number is an ascending sequence
at that value (the form before steps), and one without a start starts at its first bound.

Effects: fail, alloc.

### `sequenceOf`

```gizlang
function sequenceOf(text: string): Sequence
```

The sequence that the stored TEXT holds (see sequenceText).

Effects: fail, alloc.

### `drawAt`

```gizlang
function drawAt(q: Sequence, k: i64): i64 throws DbError
```

Draw `k` (from 0) of `q`: the k-th value from q.next on, past a bound again from the far one
with CYCLE, else an error.

Effects: fail, alloc.

### `seqFn`

```gizlang
function seqFn(op: string, d: Draw, current: Option<i64>, ordinal: i64): Scalar
```

The function NEXTVAL or CURRVAL reads. NEXTVAL takes draw number n - 1 of its argument, the
row's number in a select list (Binder.select gives it row_number()), or draw `ordinal` (an
INSERT's VALUES row; -1 elsewhere, where a row has no number). CURRVAL gives `current`, the
last value the session drew before the statement.

Effects: fail, alloc.

