# Reylo Type Defs

> A format for types, which says what values a column, a parameter or a field can hold.

A format for types.

Reylo writes the type of every parameter and column it [analyzes](https://reylo.dev/inference#how-it-works) in it. A type says which values a slot can hold, precisely enough to pick a representation in any language that holds them all.

## Types

Each type is an object with a `kind`.

Most other fields narrow the kind: a size, bounds, a pattern, a character set. A program reads `kind` and the fields it needs, and ignores the rest, since a field it doesn't know can only narrow the type or describe it. A few fields widen a type instead, each named under its kind below.

```jsonc
// A 32-bit integer from 0 to 150, which Postgres calls int4
{ "kind": "integer", "bits": 32, "min": "0", "max": "150", "label": "int4" }
```

- **Values inside a type are strings**, in the kind's canonical text, so a 64-bit bound or a date survives any encoding. Counts, such as `bits`, and code points are integers.
- **A flag appears only when it's true.** Its absence means false.
- **A label is the database's name** for the type, where it has one. It never changes what the type means.
- **A comment** is the documentation the source keeps on a named type, and **a title** is a short name written for a reader, as JSON Schema's `title`, while the label is the name the database knows the type by. Neither says anything of the values.

### Slots

Where a value stands, with whether it may be null.

A column, a parameter, a struct's field, an array's element, a tuple's element and a map's key and value are each a slot: a `type`, and `nullable` where the value may be null. Nullability is on the slot and never in the type, since an outer join makes any column nullable.

```jsonc
// Text that may be null
{ "type": { "kind": "text" }, "nullable": true }
```

## Kinds

Every type has one of these kinds:

| Kind | What it holds |
| --- | --- |
| [`boolean`](https://reylo.dev/typedefs#boolean) | A truth value |
| [`integer`](https://reylo.dev/typedefs#integer) | A whole number of a fixed width |
| [`float`](https://reylo.dev/typedefs#float) | An IEEE 754 binary float |
| [`decimal`](https://reylo.dev/typedefs#decimal) | An exact decimal |
| [`text`](https://reylo.dev/typedefs#text) | Text |
| [`bytes`](https://reylo.dev/typedefs#bytes) | Bytes |
| [`uuid`](https://reylo.dev/typedefs#uuid) | A 128-bit identifier |
| [`enum`](https://reylo.dev/typedefs#enum) | One of a list of values |
| [`date`](https://reylo.dev/typedefs#date) | A calendar date |
| [`time`](https://reylo.dev/typedefs#time) | A time of day |
| [`datetime`](https://reylo.dev/typedefs#datetime) | A date and time as a wall clock reads it |
| [`instant`](https://reylo.dev/typedefs#instant) | A point on the timeline |
| [`zoned_datetime`](https://reylo.dev/typedefs#zoned_datetime) | A point on the timeline, with its time zone |
| [`duration`](https://reylo.dev/typedefs#duration) | A length of time |
| [`array`](https://reylo.dev/typedefs#array) | Elements in order |
| [`tuple`](https://reylo.dev/typedefs#tuple) | Values in order, with no names |
| [`struct`](https://reylo.dev/typedefs#struct) | Named fields |
| [`map`](https://reylo.dev/typedefs#map) | Keys to values |
| [`table`](https://reylo.dev/typedefs#table) | Rows of columns |
| [`json`](https://reylo.dev/typedefs#json) | A JSON value |
| [`union`](https://reylo.dev/typedefs#union) | One of several types |
| [`intersection`](https://reylo.dev/typedefs#intersection) | Values of every member at once |
| [`tagged_union`](https://reylo.dev/typedefs#tagged_union) | One of several alternatives, named by a tag |
| [`range`](https://reylo.dev/typedefs#range) | A range of an ordered type |
| [`multirange`](https://reylo.dev/typedefs#multirange) | Non-overlapping ranges |
| [`geometry`](https://reylo.dev/typedefs#geometry) | An OGC simple feature |
| [`xml`](https://reylo.dev/typedefs#xml) | XML |
| [`null`](https://reylo.dev/typedefs#null) | Always null |
| [`opaque`](https://reylo.dev/typedefs#opaque) | A type the format doesn't structure |
| [`unknown`](https://reylo.dev/typedefs#unknown) | Nothing is known |

### `boolean`

A truth value.

A comparison's result is one on every database, though MySQL and SQLite deliver it as 1 or 0.

```jsonc
// Any truth value
{ "kind": "boolean" }
```

### `integer`

A whole number of a fixed width.

Its range follows from `bits`, two's complement unless `unsigned`. A bound is always inclusive, since `x > 0` is `x >= 1`.

```jsonc
// A 32-bit integer
{ "kind": "integer", "bits": 32 }

// A 64-bit unsigned integer
{ "kind": "integer", "bits": 64, "unsigned": true }

// From 0 to 150, and a multiple of 5
{ "kind": "integer", "bits": 32, "min": "0", "max": "150", "multiple_of": "5" }
```

### `float`

An [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754) binary float.

Its exponent and mantissa widths fix its range and precision, so a program picks the smallest float it has that holds both. It holds the infinities and NaN only where `infinity` and `nan` say so.

```jsonc
// A double
{ "kind": "float", "exponent_bits": 11, "mantissa_bits": 52 }

// A double that also holds Infinity, -Infinity and NaN
{ "kind": "float", "exponent_bits": 11, "mantissa_bits": 52, "infinity": true, "nan": true }

// A single-precision float above 0
{ "kind": "float", "exponent_bits": 8, "mantissa_bits": 23, "exclusive_min": "0" }
```

### `decimal`

An exact decimal.

Its `precision` counts its digits, and its scale the digits after the point. A decimal is a number, so `1.5` and `1.50` are one value.

```jsonc
// Up to 10 digits, 2 after the point
{ "kind": "decimal", "precision": 10, "min_scale": 2, "max_scale": 2 }

// Any decimal below 10^131072, NaN and the infinities too
{ "kind": "decimal", "min_scale": 0, "max_scale": 16383, "exclusive_min": "-1e131072", "exclusive_max": "1e131072", "infinity": true, "nan": true }
```

### `text`

With no `encoding`, it's any valid Unicode text. An `encoding` names the character set its values are held in, from a [fixed list](https://reylo.dev/typedefs#specification), and `ill_formed` lets them be any sequence of that set's code units, valid or not. `code_points` narrows the characters further. Its size counts code points unless its `unit` says otherwise, and a `pattern` is an [I-Regexp](https://www.rfc-editor.org/rfc/rfc9485) every value matches whole. A `format` names what the text is meant to be, by JSON Schema's format names or a source's own. It says nothing of the values, so a rule every value keeps is a `pattern`.

```jsonc
// At most 255 code points
{ "kind": "text", "size": { "max": 255 } }

// Any character but NUL, as Postgres's text holds
{ "kind": "text", "code_points": [[1, 1114111]] }

// Text with an @ in it
{ "kind": "text", "pattern": "[^@]+@[^@]+" }

// Text meant to be an email address, by JSON Schema's format name
{ "kind": "text", "format": "email" }

// Text Latin-1 holds, as MySQL's latin1 stores it
{ "kind": "text", "encoding": "windows-1252" }

// At most 65,535 bytes of UTF-8
{ "kind": "text", "encoding": "UTF-8", "size": { "unit": "byte", "max": 65535 } }

// Bytes meant as UTF-8 that nothing checked, which may not be valid Unicode
{ "kind": "text", "encoding": "UTF-8", "ill_formed": true }
```

### `bytes`

A value's length is stated where the type fixes one.

```jsonc
// Any number of bytes
{ "kind": "bytes" }

// Exactly 16 bytes
{ "kind": "bytes", "size": { "exact": 16 } }

// A PNG image
{ "kind": "bytes", "media_type": "image/png" }
```

### `uuid`

A 128-bit identifier.

It holds any 128 bits, written in [RFC 9562](https://www.rfc-editor.org/rfc/rfc9562)'s text form. Its `versions` say every value has one of those RFC 9562 versions: a UUID that `uuidv7()` or `gen_random_uuid()` makes, or a column whose `CHECK`s hold `uuid_extract_version` to one and keep it non-null. A column with a `default uuidv7()` has none, since an insert may write any UUID.

```jsonc
// Any 128 bits
{ "kind": "uuid" }

// A version 7 UUID
{ "kind": "uuid", "versions": [7] }
```

### `enum`

One of a list of values.

Its `type` is the type of every value, and its `values` the list, each in that type's canonical text. One value makes a literal, which a constant the statement writes is: `select 'user' as kind` gives the enum of `"user"`.

```jsonc
// One of two strings
{ "kind": "enum", "type": { "kind": "text" }, "values": ["happy", "sad"] }

// The integer 1
{ "kind": "enum", "type": { "kind": "integer", "bits": 32 }, "values": ["1"] }

// The literal true
{ "kind": "enum", "type": { "kind": "boolean" }, "values": ["true"] }
```

### `date`

A calendar date.

Its bounds are [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) text, with a sign and more than four digits where a year needs them. With no bounds, it runs from 0001-01-01 to 9999-12-31.

```jsonc
// Any date from 0001 to 9999
{ "kind": "date" }

// From 4714 BC to the year 5874897, and infinity and -infinity too
{ "kind": "date", "min": "-4713-11-24", "max": "+5874897-12-31", "infinity": true }
```

### `time`

A time of day.

Its `tick` is its smallest step, in seconds. It holds 24:00:00 only where its bounds say so, and keeps a UTC offset where `offset` says so.

```jsonc
// To the microsecond, up to 24:00:00
{ "kind": "time", "tick": "1/1000000", "max": "24:00:00" }

// To the second, with its UTC offset
{ "kind": "time", "tick": "1", "offset": true }
```

### `datetime`

A date and time as a wall clock reads it.

With no zone, it can't be read as an instant.

```jsonc
// To the millisecond
{ "kind": "datetime", "tick": "1/1000" }
```

### `instant`

A point on the timeline.

It's the moment alone, as [Temporal](https://tc39.es/proposal-temporal/docs/instant.html)'s `Instant` is, written in UTC however a session prints it. Its bounds are in UTC.

```jsonc
// To the microsecond, and infinity and -infinity too
{ "kind": "instant", "tick": "1/1000000", "infinity": true }
```

### `zoned_datetime`

A point on the timeline, with the time zone it was written in.

Each value keeps its zone, a region or a UTC offset, as [Temporal](https://tc39.es/proposal-temporal/docs/zoneddatetime.html)'s `ZonedDateTime` does, and is written as [RFC 9557](https://www.rfc-editor.org/rfc/rfc9557) writes one. With `offset_only`, every zone is an offset.

```jsonc
// To the millisecond, in any zone
{ "kind": "zoned_datetime", "tick": "1/1000" }

// To 100 nanoseconds, with an offset, as SQL Server's datetimeoffset keeps it
{ "kind": "zoned_datetime", "tick": "1/10000000", "offset_only": true }
```

### `duration`

A length of time.

Its parts are months, days and a time, each signed on its own, so 1 month and 30 days are two values. Its `max` is an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) duration of the parts it has, each at the largest magnitude it reaches.

```jsonc
// Months, days and a time to the microsecond
{ "kind": "duration", "max": "P2147483648M2147483648DT2562047788H54.775808S", "tick": "1/1000000" }

// A time alone, up to 838 hours, to the second
{ "kind": "duration", "max": "PT838H59M59S", "tick": "1" }
```

### `array`

Elements, in order.

Each element is a slot of its own, so it says whether it may be null. An array is flat: a two-dimensional one is an array of arrays. A [pgvector](https://github.com/pgvector/pgvector) vector is an array of floats, and a set an array whose elements never repeat, `distinct`, as MySQL's `SET` is.

```jsonc
// Integers, each of which may be null
{ "kind": "array", "element": { "type": { "kind": "integer", "bits": 32 }, "nullable": true } }

// Exactly 3 floats
{ "kind": "array", "size": { "exact": 3 }, "element": { "type": { "kind": "float", "exponent_bits": 8, "mantissa_bits": 23 } } }

// Members that never repeat
{ "kind": "array", "distinct": true, "element": { "type": { "kind": "enum", "type": { "kind": "text" }, "values": ["a", "b", "c"] } } }
```

### `tuple`

Values in order, each of its own type, with no names.

Its `elements` are always there. Its `optional_elements` may be missing from the end, and its `rest` takes any number after them.

```jsonc
// An integer, then text that may be null
{ "kind": "tuple", "elements": [{ "type": { "kind": "integer", "bits": 32 } }, { "type": { "kind": "text" }, "nullable": true }] }

// Text, then any number of integers
{ "kind": "tuple", "elements": [{ "type": { "kind": "text" } }], "rest": { "type": { "kind": "integer", "bits": 32 } } }
```

### `struct`

Named fields, in order.

Each field is a slot with a `name`. It may be `optional`, its key left out, with a `default` the key takes when it is. A struct holds exactly its fields, unless `extra` lets it hold other keys too, each a value in its slot. A field may have a `title`.

```jsonc
// A point
{
  "kind": "struct",
  "fields": [
    { "name": "x", "type": { "kind": "float", "exponent_bits": 11, "mantissa_bits": 52 } },
    { "name": "y", "type": { "kind": "float", "exponent_bits": 11, "mantissa_bits": 52 } }
  ]
}

// An optional field, with its default and its comment
{
  "kind": "struct",
  "fields": [
    { "name": "id", "type": { "kind": "integer", "bits": 64 } },
    { "name": "role", "optional": true, "default": "member", "comment": "What the user may do", "type": { "kind": "enum", "type": { "kind": "text" }, "values": ["admin", "member"] } }
  ]
}

// An open object, whose other keys hold text
{
  "kind": "struct",
  "fields": [{ "name": "id", "type": { "kind": "integer", "bits": 64 } }],
  "extra": { "type": { "kind": "text" } }
}

// A title on the struct and on a field, beside the database's name for the type
{
  "kind": "struct",
  "title": "Mailing address",
  "label": "public.address",
  "fields": [{ "name": "zip", "title": "ZIP code", "type": { "kind": "text" } }]
}
```

### `map`

Keys to values, each key once.

The key is a slot, as the value is, and the `size` counts the keys. A map whose keys may repeat is an array of `{ key, value }` structs.

```jsonc
// Text keys to text that may be null
{ "kind": "map", "key": { "type": { "kind": "text" } }, "value": { "type": { "kind": "text" }, "nullable": true } }

// At most 64 keys
{ "kind": "map", "key": { "type": { "kind": "text" } }, "value": { "type": { "kind": "integer", "bits": 32 } }, "size": { "max": 64 } }
```

### `table`

Rows of columns.

It's what a statement returns, and its `cardinality` says how many rows: `one`, `at_most_one`, `many` or `none`. Each column is a field, never optional. Where there may be many rows, `unique` lists the sets of columns no two rows share, a table's primary key first, and `order` the columns the rows are sorted on.

```jsonc
// Rows, unique by id, newest first
{
  "kind": "table",
  "cardinality": "many",
  "columns": [
    { "name": "id", "type": { "kind": "integer", "bits": 64 } },
    { "name": "created_at", "type": { "kind": "instant", "tick": "1/1000000" } }
  ],
  "unique": [["id"]],
  "order": [{ "column": "created_at", "desc": true, "nulls": "first" }]
}

// One row, a count
{ "kind": "table", "cardinality": "one", "columns": [{ "name": "n", "type": { "kind": "integer", "bits": 64 } }] }
```

### `json`

A [JSON](https://www.rfc-editor.org/rfc/rfc8259) value.

Its `content` is what a statement built, in these same types, and its `schema` a [JSON Schema](https://json-schema.org) every value satisfies. With neither, it's any JSON.

```jsonc
// Any JSON value
{ "kind": "json" }

// An object of an id and a title
{
  "kind": "json",
  "content": {
    "type": {
      "kind": "struct",
      "fields": [
        { "name": "id", "type": { "kind": "integer", "bits": 64 } },
        { "name": "title", "type": { "kind": "text" } }
      ]
    }
  }
}

// What a JSON Schema admits
{ "kind": "json", "schema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "required": ["x"] } }
```

### `union`

One of several types.

A union is flat, of two members or more, and lists its members in the order of the kinds. A union of structs that each give one field a different literal is a discriminated union, as OpenAPI's discriminator and TypeScript describe one: each value says which member it is by that field.

```jsonc
// An integer or text
{ "kind": "union", "members": [{ "kind": "integer", "bits": 64 }, { "kind": "text" }] }

// A cat or a dog, which its type field names
{
  "kind": "union",
  "members": [
    { "kind": "struct", "fields": [{ "name": "type", "type": { "kind": "enum", "type": { "kind": "text" }, "values": ["cat"] } }, { "name": "meows", "type": { "kind": "boolean" } }] },
    { "kind": "struct", "fields": [{ "name": "type", "type": { "kind": "enum", "type": { "kind": "text" }, "values": ["dog"] } }, { "name": "barks", "type": { "kind": "boolean" } }] }
  ]
}
```

### `intersection`

Values of every member at once.

It's JSON Schema's `allOf` and TypeScript's `&`. An intersection one struct can write, of structs whose fields agree or of a struct and a map with text keys, is written as that struct.

```jsonc
// A cat or a dog, with an id beside whichever it is
{
  "kind": "intersection",
  "members": [
    {
      "kind": "union",
      "members": [
        { "kind": "struct", "fields": [{ "name": "meows", "type": { "kind": "boolean" } }], "extra": { "type": { "kind": "unknown" }, "nullable": true } },
        { "kind": "struct", "fields": [{ "name": "barks", "type": { "kind": "boolean" } }], "extra": { "type": { "kind": "unknown" }, "nullable": true } }
      ]
    },
    { "kind": "struct", "fields": [{ "name": "id", "type": { "kind": "integer", "bits": 64 } }], "extra": { "type": { "kind": "unknown" }, "nullable": true } }
  ]
}
```

### `tagged_union`

One of several alternatives, each named by a tag.

Every value carries its tag beside the value, even where the value is null. Unlike a union's members, two alternatives may hold one type.

```jsonc
// A number or text, each tagged
{
  "kind": "tagged_union",
  "alternatives": [
    { "tag": "num", "type": { "kind": "integer", "bits": 32 }, "nullable": true },
    { "tag": "str", "type": { "kind": "text" }, "nullable": true }
  ]
}
```

### `range`

A range of an ordered type.

It may be empty, and either end may be unbounded.

```jsonc
// A range of instants
{ "kind": "range", "subtype": { "kind": "instant", "tick": "1/1000000" } }
```

### `multirange`

Non-overlapping ranges, in order.

```jsonc
// Ranges of integers
{ "kind": "multirange", "subtype": { "kind": "integer", "bits": 32 } }
```

### `geometry`

An [OGC simple feature](https://www.ogc.org/standards/sfa/).

It may name its model, its spatial reference, its subtype and its coordinates.

```jsonc
// A point in WGS 84, with X and Y
{ "kind": "geometry", "srid": 4326, "subtype": "point", "coordinates": "xy" }

// Any shape on the sphere
{ "kind": "geometry", "model": "geodetic" }
```

### `xml`

A document with one root, or with `fragment` several.

", "<a/><b/>"]} types={{"postgres": ["xml"]}}>

```jsonc
// A document
{ "kind": "xml" }

// A fragment, which may have several roots
{ "kind": "xml", "fragment": true }
```

### `null`

Always null.

It stands in a nullable slot, for a value a statement always writes as null.

```jsonc
// The field a json_build_object('a', null) writes
{ "kind": "null" }
```

### `opaque`

A type the format doesn't structure.

Its `label` is all the format says. A program that meets a kind it doesn't know reads it as this one.

```jsonc
// A Postgres extension's type, known by its name
{ "kind": "opaque", "label": "ltree" }
```

### `unknown`

Nothing is known about the values.

A parameter nothing in the statement types is one, where [`allow_untyped_params`](https://reylo.dev/configuration#allow_untyped_params) lets it through.

```jsonc
// Any value
{ "kind": "unknown" }
```

## Specification
