MySQL

How Reylo types queries on MySQL

Reylo is an engine that infers the types of SQL queries from your live database, for TypeScript.

MySQL versions8.0.38 or later; tested on 8.0.38 and 8.4
ConnectionA mysql:// URL in DATABASE_URL or direct_url
Driversmysql2, mariadb, PlanetScale and Bun.sql, Drizzle over mysql2 or PlanetScale, and Knex over mysql2 or mariadb (Drivers)
Type checkingReylo's engine connects to MySQL itself, so your project needs no driver for it

Where types come from

Reylo types each query from MySQL's own analysis of it.

Reylo sends each query to your live database prepared to read MySQL's parameter and column types. It then infers parameter nullability, row counts and built JSON shapes.

Data types

Each MySQL type has one TypeScript type.

In TypeScript, .run() returns the same value for a type on every driver. The exceptions are a FLOAT's last digits and what Bun.sql loses:

SQL typeTypeScriptThe value .run() returns
TINYINT, SMALLINT, MEDIUMINT, INT, YEARnumber2026
BIGINT, BIGINT UNSIGNED, COUNT(*)bigint9007199254740993n
BOOLEAN (a TINYINT(1)), BIT(1)booleantrue
A comparison, IS NULL, IN, BETWEEN, LIKE, EXISTS, NOT, AND, ORbooleanfalse
DECIMAL, SUM(…), AVG(…), /string"12.50"
FLOAT, DOUBLEnumber1.1
CHAR, VARCHAR, TEXTstring"Ada"
ENUMthe union of its labels"member"
SETa Set of its labels, its members in the order the column declares themnew Set(["a", "c"])
DATEstring"2026-10-20"
DATETIME, TIMESTAMPstring"2026-10-20T10:00:00.123"
TIMEstring"10:00:00"
JSONJson{ a: 1 }
JSON a JSON Schema CHECK holdswhat the schema admits{ x: 10 }
json_object(…), json_arrayagg(…)the object or array it builds{ total: 12.5 }
BINARY, VARBINARY, BLOB, BIT wider than 1Uint8ArrayUint8Array.of(1, 2, 255)
GEOMETRYunknownits bytes, a Uint8Array
VECTORnumber[][1, 2.5, -3]

In TypeScript, each example below pairs a SQL value with the value .run() returns for it: select <SQL> as v returns the row { v: <JavaScript> }.

Integers

A BIGINT, signed or unsigned, comes back as a JavaScript bigint. So do COUNT(*) and most integer expressions, such as id + 1 and length(name), since MySQL computes them as BIGINT. To get a number, cast to double:

import  from "./my_count_orders.sql";

const counts = await .();
const counts: {
    total: bigint;
    total_number: number;
}
select count(*) as total, cast(count(*) as double) as total_number
from 

When an expression's type depends on the value you pass, it's typed as every type it could be. For example, MySQL may compute :n + 1 as a BIGINT, a DOUBLE or a DECIMAL, so it's bigint | number | string.

SQL
CAST(1 AS SIGNED) + 1
JavaScript
2n
SQL
CAST(1.5 AS DOUBLE) + 1
JavaScript
2.5
SQL
CAST(1.5 AS DECIMAL(2,1)) + 1
JavaScript
"2.5"

Decimals

A DECIMAL comes back as its exact text, keeping the column's scale. So do SUM(…), AVG(…) and division, since MySQL computes them as DECIMAL: sum(total) returns "19.75", and id / 2 returns "0.5000".

A FLOAT is a 32-bit float. On mysql2 it comes back as its exact value. The mariadb driver, PlanetScale and Bun.sql may round it to its shorter text, such as 1.1. A DOUBLE is the same on every driver.

SQL
CAST(1.1 AS FLOAT)
JavaScript
1.100000023841858
SQL
CAST(1.1 AS DOUBLE)
JavaScript
1.1

Dates and times

No value comes back as a Date. Each is the text MySQL writes, with a T between the date and the time:

import  from "./my_order_dates.sql";

const order = await .(, { : 1 });
const order: {
    placed_at: string;
    ships_on: string | null;
} | null
select placed_at, ships_on from  where id = :id

If your runtime has Temporal, read the value with Temporal.PlainDateTime.from().

Fractions of a second

A value has as many fraction digits as its type. A DATETIME(3) always has three, and a DATETIME has none.

SQL
CAST('2026-10-20 10:00:00.123456' AS DATETIME(6))
JavaScript
"2026-10-20T10:00:00.123456"
SQL
CAST('2026-10-20 10:00:00' AS DATETIME(3))
JavaScript
"2026-10-20T10:00:00.000"
SQL
CAST('2026-10-20 10:00:00' AS DATETIME)
JavaScript
"2026-10-20T10:00:00"
  • A TIMESTAMP's zone. MySQL returns a TIMESTAMP in the session's time_zone, which Reylo can't know, so the text has no zone. To read UTC, run set time_zone = '+00:00' on the connection. Or store UTC in a DATETIME with utc_timestamp(), as the schema above does.
  • Year 0000. MySQL's default sql_mode refuses 0000-00-00, but stores a date in year 0000, and date arithmetic reaches one: last_day('0000-02-01') is "0000-02-28". So a DATE's and a DATETIME's type descriptors start at 0000-01-01.

Truth values

MySQL has no boolean type: a BOOLEAN column is a TINYINT(1), and a comparison returns 1 or 0. Reylo types TINYINT(1) and BIT(1) columns as boolean, and every comparison your query makes:

import  from "./my_user_flags.sql";

const rows = await .();
const rows: {
    id: number;
    active: boolean;
    is_admin: boolean;
}[]
select id, active, role = 'admin' as is_admin from 

How MySQL counts a boolean:

What counts

Comparisons and logical operators are typed boolean:

= <> < > in between like regexp exists
is not and or xor || true false
-- and a case, if, coalesce, ifnull, nullif or subquery of them

The || operator joins strings instead where your sql_mode has PIPES_AS_CONCAT.

SQL
'Ada' LIKE 'B%'
JavaScript
false
SQL
IF(1 = 1, TRUE, FALSE)
JavaScript
true

Where MySQL hides the column

A boolean column stays boolean through a subquery in from or a with query. It becomes a number where MySQL hides the column, such as through a view or in max(active).

SQL
TRUE + 0
JavaScript
1n
SQL
max(1 = 1)
JavaScript
1n
SQL
(SELECT b FROM (SELECT 1 = 1 AS b) d)
JavaScript
1n
  • Values other than 0 and 1. A TINYINT(1) can hold any number from −128 to 127. Reylo reads 0 and 1 as false and true, and throws an error naming the column for any other value. Store only 0 or 1, or read the number with active + 0.

JSON

A JSON column is typed Json, any JSON value. A JSON_SCHEMA_VALID check narrows it, and so does JSON your query builds. Reylo exports the type:

type Json = string | number | boolean | null | { [key: string]: Json | undefined } | Json[];

A constrained column gets its schema's type:

import  from "./my_events.sql";

const rows = await .();
const rows: {
    kind: string;
    payload: {
        x: number;
        code?: string;
    };
}[]
select kind, payload from 

JSON your query builds with json_object and json_arrayagg is typed from what you put in it:

import  from "./my_order_summaries.sql";

const rows = await .();
const rows: {
    name: string;
    summary: {
        total: number;
        placed_at: string;
    };
}[]
select u.name,
  json_object('total', o.total, 'placed_at', o.placed_at) as summary
from  o
join  u on u.id = o.user_id

Inside json_object, an aggregate can sit beside the query's columns wherever its group by allows. So json_object('name', u.name, 'posts', count(*)) with group by u.id is { name: string; posts: number }. A group by 1 or by an alias gives such an object Json values. A JSON column inside built JSON may be null, even when NOT NULL, since it can hold JSON's null.

A schema's type carries through json_arrayagg:

import  from "./my_events_by_kind.sql";

const groups = await .();
const groups: {
    kind: string;
    payloads: {
        x: number;
        code?: string;
    }[];
}[]
select kind, json_arrayagg(payload) as payloads
from 
group by kind

What changes inside JSON:

Values inside a document

Inside JSON, a value can differ from the same value in a column. Numbers past 2^53 lose precision in JSON.parse. A DATETIME is MySQL's text, and a boolean may be true or 1.

SQL
CAST('{"n": 9007199254740993}' AS JSON)
JavaScript
{ n: 9007199254740992 }
SQL
json_object('at', CAST('2026-10-20 10:00:00' AS DATETIME))
JavaScript
{ at: "2026-10-20 10:00:00.000000" }
SQL
json_object('b', 1 = 1)
JavaScript
{ b: true }
SQL
json_object('b', max(1 = 1))
JavaScript
{ b: 1 }

Where a schema's type applies

A schema's type reaches the column when you select it straight from its table, and inside json_object or json_arrayagg. Anywhere else, such as through a subquery or in an expression, it's Json.

Query
select json_object('p', payload) as wrapped,
  json_extract(payload, '$.x') as x
from 
Params
void
Returns
{ wrapped: { p: { x: number; code?: string } }; x: Json }[]

An empty array as a default

Over no rows, json_arrayagg returns NULL. A default of an empty array keeps the array's type:

Query
select coalesce(json_arrayagg(id), json_array()) as ids
from 
where user_id = :user_id
Params
{ user_id: number }
Returns
{ ids: number[] }

MySQL validates every schema as draft 4, whatever its $schema says. So const, if, prefixItems and contains don't narrow the type.

Enums and sets

An ENUM is the union of its labels, and a SET a JavaScript Set of them.

MySQL keeps a SET's members once each, in the order the column declares them. A parameter written to a SET column, or compared with one, takes a Set too. To send a Set as JSON, spread it into an array first, since JSON has no sets.

SQL
'c,a,a' in a SET('a', 'b', 'c') column
JavaScript
new Set([ "a", "c" ])
SQL
'' in the same column
JavaScript
new Set()

MySQL stores '' in an ENUM for a value it doesn't list, under INSERT IGNORE or outside strict mode. Calling .run() on such a row throws, naming the column. Select nullif(column, '') to read it.

Vectors

A VECTOR, new in MySQL 9, comes back as a number[] of 32-bit floats. A vector parameter takes a number[], and rejects NaN and infinities before the query runs.

SQL
STRING_TO_VECTOR('[1, 2.5, 0.1]')
JavaScript
[1, 2.5, 0.10000000149011612]

Nullability

Each column can be null unless Reylo can tell it never is. On MySQL:

  • The server's flags. Reylo starts from whether MySQL reports each column NOT NULL. MySQL is cautious with string and date functions, most casts and division, which stay nullable even over a NOT NULL column: length(name) is never null, and upper(name) can be.
  • Tests through coalesce, ifnull and <=> don't make their column non-null, and neither does a test under an or that tests another column.
  • bit_and, bit_or and bit_xor are never null, even over no rows. Neither are json_arrayagg and json_objectagg in a group or over a window.
  • WITH ROLLUP adds summary rows whose grouped columns are NULL, so their types include null.
  • An aggregate in a subquery that reads only the outer query's columns aggregates the outer query. An example is count(u.name) in (select count(u.name) from posts). The outer query then returns one row even where it reads none.

To say a value is never null, write coalesce(x, …), ifnull(x, …) or where x is not null.

Cardinality

Reylo infers how many rows a query returns. On MySQL:

  • A write returns nothing. MySQL has no returning, so every write is void, as is select … into @variable.
  • values row(…) of one row returns that row.
  • A key matches exactly or not at all. It doesn't count where MySQL compares loosely:
    • under a collation it picks, as beside a cast(… as char)
    • as doubles, as beside a float, or a string beside a number
    • on a TIMESTAMP, which two instants share when clocks go back
    • under WITH ROLLUP
  • An unnamed expression among several columns is a type error where its text isn't an identifier, as with count(*): MySQL names the column by that text, which a driver that writes values into the statement fills in. Name it with as.

To read a new row's id, select last_insert_id() on the connection that ran the insert:

import  from "mysql2/promise";
import  from "./my_last_insert_id.sql";

const  = .(..);
const  = await .();
// … run an insert on conn, then:
const { id } = await .();
const id: bigint
.();
select last_insert_id() as id

Parameters

Parameters are non-null by default and bound to the types inferred from how the query uses them.

Placeholders

Write parameters as :name, and pass .run() an object with those names. You can use MySQL's ? instead, but not both in one query. Then .run() takes an object keyed by number, { 1: 42 }.

What a parameter takes

A parameter accepts the same values .run() returns for its type. You can pass a row straight into the next query:

SQL typeA parameter takes
TINYINT, SMALLINT, MEDIUMINT, INT, YEARnumber
A BIGINT columnnumber, bigint or a string of digits
A TINYINT(1) or BIT(1) columnboolean or number
DECIMALstring
FLOAT, DOUBLEnumber
CHAR, VARCHAR, TEXTstring
An ENUM columnthe union of its labels
A SET columna Set of its labels
DATE, DATETIME, TIMESTAMP, TIMEstring
JSONany value JSON.stringify writes, such as a Date inside an object
BINARY, VARBINARY, BLOBUint8Array
VECTORnumber[]

How each type comes back:

Integers

MySQL reports every integer parameter as a BIGINT. So Reylo types it from the column it's compared with or written to. Elsewhere it uses MySQL's type, as for limit:

Query
select name
from 
where id > :after
limit :n
Params
{ after: number; n: number }
Returns
{ name: string }[]

Dates and times

A date or time parameter takes the text, never a Date, since drivers convert a Date in different time zones:

import  from "./my_orders_since.sql";

await .(, { : "2026-10-12 19:06:48" });
select id from  where placed_at > :since

A BINARY, VARBINARY or BLOB parameter takes only a Uint8Array. It rejects base64 or hex text, which MySQL would store as the text's own bytes. Decode the text into a Uint8Array first.

  • A JSON parameter is sent as JSON, so a string is stored as a JSON string: '{"a":1}' becomes "{\"a\":1}".
  • MySQL reads JSON as a document only when written to a column, passed to a JSON function, or cast. Anywhere else, as in json_set(doc, '$.name', :name), it would store the text as a string. So the query is a type error until you cast the parameter: :name::json.
  • Where the query takes no null for a JSON parameter, null is JSON's null. To keep doc for null, write coalesce(:doc::nullable(json), doc).

Parameters that may be null

A parameter accepts null in two places. Such a parameter is optional in .run(), and leaving it out passes null.

Cast to nullable(…)

A cast to nullable(type) makes the parameter that type or null.

Query
select id, name
from 
where role = coalesce(:role::nullable(text), role)
Params
{ role?: string | null }
Returns
{ id: number; name: string }[]

Written to a nullable column

Written directly into a column that accepts NULL, with no cast. A column accepts it unless it's NOT NULL or a check (… is not null) covers it. It also refuses NULL when a NOT NULL generated column computes from it, as nu + 1 does.

Query
insert into  (user_id, total, ships_on)
values (:user_id, :total, :ships_on)
Params
{ user_id: number; total: string; ships_on?: string | null }
Returns
void

Any other cast sets the parameter's whole type, so :email::text never accepts null. Neither coalesce nor a null test makes a parameter nullable. A nullable(…) parameter written to a column that refuses null is an error.

Casts

MySQL has no :: casts, so Reylo turns :p::type into MySQL's CAST. It also checks your value against the type before the query runs. MySQL's CAST would silently turn a bad value into 0 or NULL. MySQL's own cast(:p as …) works too.

You writeMySQL runs
::int, ::bigint, ::smallintCAST(? AS SIGNED)
::int unsignedCAST(? AS UNSIGNED)
::numeric(10,2), ::decimal(10,2)CAST(? AS DECIMAL(10,2))
::real, ::double precisionCAST(? AS FLOAT), CAST(? AS DOUBLE)
::text, ::varchar(20), ::uuid?, typed as text, since it then takes the collation of the column it meets
::date, ::time, ::datetimeCAST(? AS DATE), CAST(? AS TIME), CAST(? AS DATETIME(6))
::jsonCAST(? AS JSON)
::bytea, ::blobCAST(? AS BINARY)
::int in limit or offset?, since MySQL takes only a bare value there
::timestamptz, ::booleanAn error: MySQL has neither type

The check rejects an integer out of range, a decimal with too many digits, and a date that doesn't exist.

A json_table text column takes your database's collation. MySQL would give it the connection's, and comparing it with a column would fail with "Illegal mix of collations". A type that names its own collate is left as you wrote it. Prefer ::text over cast(… as char), which takes the connection's collation.

Database errors

With .try(), an error MySQL raised comes back as { error }, with the same fields on every driver:

FieldWhat it holds
codeThe error's name, as "ER_DUP_ENTRY", from the 1,777 that MySQL 8.4 sends a client, or undefined for a number it doesn't define, such as one a signal sets
errnoThe error's number, as 1062
sqlStateThe SQLSTATE, as "23000"
messageThe server's message
keyOn a duplicate entry, the key as the message names it, as users.email
constraintOn a foreign key or a check the row fails, the constraint
tableOn a foreign key the row fails, the table it belongs to
columnOn a null, a missing value, or a value too long or out of range, the column

Reylo names the error from MySQL's own list, whichever driver ran it. MySQL names a key, a constraint or a column only in its message. Reylo reads it in English, so with another lc_messages language those fields are undefined.

When the query fires no trigger and calls no stored function, its error type is narrowed. A duplicate entry names only the unique keys of the tables it writes. Other errors name only their constraints and columns.

Drivers

Reylo decodes its query results itself, so your client's options don't affect Reylo's queries, or the reverse. Type checking reads your schema over its own connection, whatever driver your app uses.

Each example below runs this query:

select id, name, email from  where id = :id

mysql2

Pass a pool or a connection, from either API. A connection taken from a pool can run a transaction:

import  from "mysql2/promise";
import  from "mysql2";
import  from "./my_get_user.sql";

const  = .(..);
const  = await .(, { : 1 });

const  = await .();
await .();
await .(, { : 1 });
await .();
.();

const  = .(..);
await .(, { : 1 });

Reylo runs each query through mysql2's execute(), which prepares it first. Where the server refuses prepared statements, as Hyperdrive does, Reylo writes the values into the statement and uses query():

  • A FLOAT column comes back with the 6 significant digits MySQL sends as text, so 1.100000023841858 reads as 1.1.
  • A custom queryFormat is refused there, since it would rewrite each statement. So is a non-ASCII value on a connection whose charset isn't UTF-8.

mariadb

The mariadb driver works with a MySQL server. The type check refuses a MariaDB server. It takes only a mariadb:// URL, which Reylo reads as MySQL. Pass a pool or a connection, from either API. A connection taken from a pool can run a transaction:

import  from "mariadb";
import  from "mariadb/callback";
import  from "./my_get_user.sql";

const  = .(..);
const  = await .(, { : 1 });

const  = await .();
await .();
await .(, { : 1 });
await .();
await .();

const  = .(..);
await .(, { : 1 });

Reylo runs each query through its query() method, which prepares nothing. So it also works through Cloudflare Hyperdrive, in a Worker with Node's APIs. Connect it with the fields of the binding:

import  from "mariadb";
import  from "./my_get_user.sql";

export default {
  async (: , : { : Hyperdrive }) {
    const { , , , ,  } = .;
    const  = await .({ , , , ,  });
    const  = await .(, { : 1 });
    await .();
    return .();
  },
};

PlanetScale

Pass a connection, or the transaction it hands its callback:

// @planetscale/database 1.x: a 2.0 client is a type error
import {  } from "@planetscale/database";
import  from "./my_get_user.sql";

const  = ({ : .. });
const  = await .(, { : 1 });

await .(() => .(, { : 1 }));

Version 2.0 isn't supported, since it can't bind parameters.

Bun.sql

Pass the client, or a transaction, savepoint or reserved connection taken from it:

import {  } from "bun";
import  from "./my_get_user.sql";

const  = new (..);
const  = await .(, { : 1 });

await .(async () => {
  await .(, { : 1 });
  await .(() => .(, { : 1 }));
});

const  = await .();
await .(, { : 1 });
.();

Bun loses the microseconds of a DATETIME before Reylo sees them. Before Bun 1.4.4, it also drops all-zero and TIME fractions, and can return a DECIMAL as a bigint. Bun 1.4 can't read a VECTOR at all, so select vector_to_string(v) instead.

Drizzle

Pass a Drizzle connection made over mysql2 or PlanetScale, or a transaction or savepoint taken from it:

import {  } from "drizzle-orm/mysql2";
import  from "./my_get_user.sql";

const  = (..);
const  = await .(, { : 1 });

await .(async () => {
  await .(, { : 1 });
  await .(() => .(, { : 1 }));
});

Knex

Pass a Knex instance over mysql2 or mariadb, or a transaction or savepoint taken from it. Each query runs on a connection from the instance's pool, or on the transaction's own:

import  from "knex";
import  from "./my_get_user.sql";

const  = ({ : "mysql2", : .. });
const  = await .(, { : 1 });

await .(async () => {
  await .(, { : 1 });
  await .(() => .(, { : 1 }));
});

Limits

What Reylo can't type on MySQL, and what to do instead:

LimitInstead
The labels of an ENUM or a SET a query reads through an expression or a recursive WITH query, of an ENUM through a UNION with a side of another type, and of a SET through any UNION: it is typed string, or Set<string>Select the column itself where you need the union
Where in a query an error is, which MySQL doesn't sayNone: the type check marks the whole query
An if or a case that returns a BIT column, which MySQL sends as the column's bytes under a DECIMAL type, or as a number under a BIT one: it is typed unknownMake the column a number first: if(n > 0, enabled + 0, 0)
A coalesce, ifnull, greatest, least or any_value of BIT columns alone, which MySQL sends as the number's decimal digits under a BIT type, in a column or inside JSON: it is typed unknownMake the column a number first: coalesce(mask + 0, 0)
A BIT that a view, a derived table or a WITH query computes, which MySQL sends as bytes or as decimal digits by what computes it: read as a column, it is typed unknownMake it a number where it is computed: max(mask) + 0
A loadable function (create function … soname), which information_schema doesn't list, so .readOnly can't see oneDon't retry a query that calls one
A query Reylo's parser can't readNone: it keeps MySQL's types, every column can be null, it returns Row[], and its JSON is Json
A query MySQL reads otherwise than Reylo's parser, by its sql_mode (count (x) without IGNORE_SPACE, not under HIGH_NOT_PRECEDENCE) or by a SET_VAR hintNone: Reylo keeps MySQL's types, every column can be null, and it has no row counts or JSON shapes
A /*! … */ comment, which MySQL runs as SQL, so it's an errorWrite it as plain SQL
with … insert, which MySQL 8.4 rejectsPut the with after insert into … (…), as in Bulk inserts
A chain of more than 2,000 operators, as in a or b or … or union all, or a query nested past 200 levelsNone: Reylo falls back to MySQL's own types, every column can be null, and any number of rows. The query's hover says why
A statement other than a query, such as create index or show tablesNone: it returns nothing, or rows whose columns are all nullable, as MySQL reports
explain and call, whose rows MySQL describes only once they runNone: each is an error
A file of several statements, such as a migrationPut each statement in a file of its own
Released under the MIT License. Copyright © 2026 Colin McDonnell.

On this page

reylosql/reylo