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 versions | 8.0.38 or later; tested on 8.0.38 and 8.4 |
| Connection | A mysql:// URL in DATABASE_URL or direct_url |
| Drivers | mysql2, mariadb, PlanetScale and Bun.sql, Drizzle over mysql2 or PlanetScale, and Knex over mysql2 or mariadb (Drivers) |
| Type checking | Reylo'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 type | TypeScript | The value .run() returns |
|---|---|---|
TINYINT, SMALLINT, MEDIUMINT, INT, YEAR | number | 2026 |
BIGINT, BIGINT UNSIGNED, COUNT(*) | bigint | 9007199254740993n |
BOOLEAN (a TINYINT(1)), BIT(1) | boolean | true |
A comparison, IS NULL, IN, BETWEEN, LIKE, EXISTS, NOT, AND, OR | boolean | false |
DECIMAL, SUM(…), AVG(…), / | string | "12.50" |
FLOAT, DOUBLE | number | 1.1 |
CHAR, VARCHAR, TEXT | string | "Ada" |
ENUM | the union of its labels | "member" |
SET | a Set of its labels, its members in the order the column declares them | new Set(["a", "c"]) |
DATE | string | "2026-10-20" |
DATETIME, TIMESTAMP | string | "2026-10-20T10:00:00.123" |
TIME | string | "10:00:00" |
JSON | Json | { a: 1 } |
JSON a JSON Schema CHECK holds | what the schema admits | { x: 10 } |
json_object(…), json_arrayagg(…) | the object or array it builds | { total: 12.5 } |
BINARY, VARBINARY, BLOB, BIT wider than 1 | Uint8Array | Uint8Array.of(1, 2, 255) |
GEOMETRY | unknown | its bytes, a Uint8Array |
VECTOR | number[] | [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 .();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.
CAST(1 AS SIGNED) + 12nCAST(1.5 AS DOUBLE) + 12.5CAST(1.5 AS DECIMAL(2,1)) + 1"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.
CAST(1.1 AS FLOAT)1.100000023841858CAST(1.1 AS DOUBLE)1.1Dates 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 });select placed_at, ships_on from where id = :idIf 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.
CAST('2026-10-20 10:00:00.123456' AS DATETIME(6))"2026-10-20T10:00:00.123456"CAST('2026-10-20 10:00:00' AS DATETIME(3))"2026-10-20T10:00:00.000"CAST('2026-10-20 10:00:00' AS DATETIME)"2026-10-20T10:00:00"- A
TIMESTAMP's zone. MySQL returns aTIMESTAMPin the session'stime_zone, which Reylo can't know, so the text has no zone. To read UTC, runset time_zone = '+00:00'on the connection. Or store UTC in aDATETIMEwithutc_timestamp(), as the schema above does. - Year 0000. MySQL's default
sql_moderefuses0000-00-00, but stores a date in year 0000, and date arithmetic reaches one:last_day('0000-02-01')is"0000-02-28". So aDATE's and aDATETIME'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 .();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 themThe || operator joins strings instead where your sql_mode has PIPES_AS_CONCAT.
'Ada' LIKE 'B%'falseIF(1 = 1, TRUE, FALSE)trueWhere 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).
TRUE + 01nmax(1 = 1)1n(SELECT b FROM (SELECT 1 = 1 AS b) d)1n- Values other than 0 and 1. A
TINYINT(1)can hold any number from −128 to 127. Reylo reads 0 and 1 asfalseandtrue, and throws an error naming the column for any other value. Store only 0 or 1, or read the number withactive + 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 .();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 .();select u.name,
json_object('total', o.total, 'placed_at', o.placed_at) as summary
from o
join u on u.id = o.user_idInside 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 .();select kind, json_arrayagg(payload) as payloads
from
group by kindWhat 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.
CAST('{"n": 9007199254740993}' AS JSON){ n: 9007199254740992 }json_object('at', CAST('2026-10-20 10:00:00' AS DATETIME)){ at: "2026-10-20 10:00:00.000000" }json_object('b', 1 = 1){ b: true }json_object('b', max(1 = 1)){ 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.
select json_object('p', payload) as wrapped,
json_extract(payload, '$.x') as x
from void{ 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:
select coalesce(json_arrayagg(id), json_array()) as ids
from
where user_id = :user_id{ user_id: number }{ 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.
'c,a,a' in a SET('a', 'b', 'c') columnnew Set([ "a", "c" ])'' in the same columnnew 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.
STRING_TO_VECTOR('[1, 2.5, 0.1]')[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 aNOT NULLcolumn:length(name)is never null, andupper(name)can be. - Tests through
coalesce,ifnulland<=>don't make their column non-null, and neither does a test under anorthat tests another column. bit_and,bit_orandbit_xorare never null, even over no rows. Neither arejson_arrayaggandjson_objectaggin a group or over a window.WITH ROLLUPadds summary rows whose grouped columns areNULL, so their types includenull.- 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 isvoid, as isselect … 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
- under a collation it picks, as beside a
- 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 withas.
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 .();.();select last_insert_id() as idParameters
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 type | A parameter takes |
|---|---|
TINYINT, SMALLINT, MEDIUMINT, INT, YEAR | number |
A BIGINT column | number, bigint or a string of digits |
A TINYINT(1) or BIT(1) column | boolean or number |
DECIMAL | string |
FLOAT, DOUBLE | number |
CHAR, VARCHAR, TEXT | string |
An ENUM column | the union of its labels |
A SET column | a Set of its labels |
DATE, DATETIME, TIMESTAMP, TIME | string |
JSON | any value JSON.stringify writes, such as a Date inside an object |
BINARY, VARBINARY, BLOB | Uint8Array |
VECTOR | number[] |
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:
select name
from
where id > :after
limit :n{ after: number; n: number }{ 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 > :sinceA 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,
nullis JSON'snull. To keepdocfornull, writecoalesce(: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.
select id, name
from
where role = coalesce(:role::nullable(text), role){ role?: string | null }{ 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.
insert into (user_id, total, ships_on)
values (:user_id, :total, :ships_on){ user_id: number; total: string; ships_on?: string | null }voidAny 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 write | MySQL runs |
|---|---|
::int, ::bigint, ::smallint | CAST(? AS SIGNED) |
::int unsigned | CAST(? AS UNSIGNED) |
::numeric(10,2), ::decimal(10,2) | CAST(? AS DECIMAL(10,2)) |
::real, ::double precision | CAST(? 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, ::datetime | CAST(? AS DATE), CAST(? AS TIME), CAST(? AS DATETIME(6)) |
::json | CAST(? AS JSON) |
::bytea, ::blob | CAST(? AS BINARY) |
::int in limit or offset | ?, since MySQL takes only a bare value there |
::timestamptz, ::boolean | An 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:
| Field | What it holds |
|---|---|
code | The 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 |
errno | The error's number, as 1062 |
sqlState | The SQLSTATE, as "23000" |
message | The server's message |
key | On a duplicate entry, the key as the message names it, as users.email |
constraint | On a foreign key or a check the row fails, the constraint |
table | On a foreign key the row fails, the table it belongs to |
column | On 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 = :idmysql2
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
FLOATcolumn comes back with the 6 significant digits MySQL sends as text, so1.100000023841858reads as1.1. - A custom
queryFormatis 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:
| Limit | Instead |
|---|---|
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 say | None: 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 unknown | Make 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 unknown | Make 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 unknown | Make 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 one | Don't retry a query that calls one |
| A query Reylo's parser can't read | None: 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 hint | None: 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 error | Write it as plain SQL |
with … insert, which MySQL 8.4 rejects | Put 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 levels | None: 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 tables | None: it returns nothing, or rows whose columns are all nullable, as MySQL reports |
explain and call, whose rows MySQL describes only once they run | None: each is an error |
| A file of several statements, such as a migration | Put each statement in a file of its own |