// A MySQL client over any byte exchange: the other side of ./stream.ts, so a journey speaks the wire as an application's // driver does (mysql_async under Prisma's engines): protocol v10 with mysql_native_password, text queries, and prepared // statements with binary parameters and rows. It reads what the protocol answers; it decides nothing. // source: https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_basics.html import { MysqlType, MysqlFlag, nativePasswordToken, type MysqlError } from './stream.ts'; /** Sends bytes and returns every byte the server answered to them. */ export type MysqlExchange = (bytes: Uint8Array) => Promise; export type MysqlResultSet = { columns: { name: string; type: number; flags: number }[]; rows: (string | null)[][] }; export type MysqlAnswer = MysqlResultSet | { affectedRows: number; insertId: number } | { error: MysqlError }; const enc = new TextEncoder(); const dec = new TextDecoder(); const CLIENT_CAPS = 0x1 | 0x4 | 0x8 | 0x200 | 0x2000 | 0x8000 | 0x10000 | 0x20000 | 0x40000 | 0x80000 | 0x200000; function packet(seq: number, payload: Uint8Array): Uint8Array { const out = new Uint8Array(4 + payload.length); out[0] = payload.length & 0xff; out[1] = (payload.length >> 8) & 0xff; out[2] = (payload.length >> 16) & 0xff; out[3] = seq; out.set(payload, 4); return out; } function packets(bytes: Uint8Array): Uint8Array[] { const out: Uint8Array[] = []; let at = 0; while (at + 4 <= bytes.length) { const len = bytes[at]! | (bytes[at + 1]! << 8) | (bytes[at + 2]! << 16); out.push(bytes.subarray(at + 4, at + 4 + len)); at += 4 + len; } return out; } class Cursor { at = 0; constructor(readonly b: Uint8Array) {} u8(): number { return this.b[this.at++]!; } u16(): number { return this.u8() | (this.u8() << 8); } u32(): number { return (this.u16() | (this.u16() << 16)) >>> 0; } u64(): bigint { let n = 0n; for (let i = 0n; i < 8n; i++) n |= BigInt(this.u8()) << (8n * i); return n; } take(n: number): Uint8Array { const out = this.b.subarray(this.at, this.at + n); this.at += n; return out; } nul(): string { const end = this.b.indexOf(0, this.at); const s = dec.decode(this.b.subarray(this.at, end)); this.at = end + 1; return s; } lenenc(): number { const f = this.u8(); if (f < 0xfb) return f; if (f === 0xfc) return this.u16(); if (f === 0xfd) return this.u16() | (this.u8() << 16); return Number(this.u64()); } lenencStr(): string { return dec.decode(this.take(this.lenenc())); } } const errorOf = (p: Uint8Array): MysqlError => { const c = new Cursor(p); c.u8(); const errno = c.u16(); c.u8(); // '#' const sqlstate = dec.decode(c.take(5)); return { errno, sqlstate, message: dec.decode(c.take(p.length - c.at)) }; }; function column(p: Uint8Array): { name: string; type: number; flags: number } { const c = new Cursor(p); c.lenencStr(); c.lenencStr(); c.lenencStr(); c.lenencStr(); // catalog, schema, table, org_table const name = c.lenencStr(); c.lenencStr(); c.lenenc(); // org_name, fixed-length 0x0c c.u16(); c.u32(); const type = c.u8(); const flags = c.u16(); return { name, type, flags }; } const pad = (n: number, w = 2) => String(n).padStart(w, '0'); /** A binary row's value as MySQL's text protocol writes it, so a journey reads both protocols alike. */ function binaryValue(c: Cursor, type: number, flags: number): string { const unsigned = (flags & MysqlFlag.UNSIGNED) !== 0; switch (type) { case MysqlType.TINY: { const v = c.u8(); return String(unsigned ? v : (v << 24) >> 24); } case MysqlType.SHORT: case MysqlType.YEAR: { const v = c.u16(); return String(unsigned ? v : (v << 16) >> 16); } case MysqlType.LONG: case MysqlType.INT24: { const v = c.u32(); return String(unsigned ? v : v | 0); } case MysqlType.LONGLONG: { const v = c.u64(); return String(unsigned ? v : BigInt.asIntN(64, v)); } case MysqlType.FLOAT: { const b = c.take(4); return String(new DataView(b.buffer, b.byteOffset, 4).getFloat32(0, true)); } case MysqlType.DOUBLE: { const b = c.take(8); return String(new DataView(b.buffer, b.byteOffset, 8).getFloat64(0, true)); } case MysqlType.DATE: case MysqlType.DATETIME: case MysqlType.TIMESTAMP: { const len = c.u8(); if (!len) return type === MysqlType.DATE ? '0000-00-00' : '0000-00-00 00:00:00'; const y = c.u16(), m = c.u8(), d = c.u8(); const [h, i, s] = len >= 7 ? [c.u8(), c.u8(), c.u8()] : [0, 0, 0]; const us = len >= 11 ? c.u32() : 0; const day = `${pad(y, 4)}-${pad(m)}-${pad(d)}`; return type === MysqlType.DATE ? day : `${day} ${pad(h)}:${pad(i)}:${pad(s)}${us ? `.${pad(us, 6)}` : ''}`; } case MysqlType.TIME: { const len = c.u8(); if (!len) return '00:00:00'; const neg = c.u8(), days = c.u32(), h = c.u8(), i = c.u8(), s = c.u8(); const us = len >= 12 ? c.u32() : 0; return `${neg ? '-' : ''}${pad(days * 24 + h)}:${pad(i)}:${pad(s)}${us ? `.${pad(us, 6)}` : ''}`; } default: return c.lenencStr(); } } /** One command's answer: an OK, an ERR, or a result set (text or binary rows). */ function answer(payloads: Uint8Array[], binary: boolean): MysqlAnswer { const first = payloads[0]; if (!first) return { error: { errno: 2013, sqlstate: 'HY000', message: 'Lost connection to MySQL server during query' } }; if (first[0] === 0xff) return { error: errorOf(first) }; // a result set begins with its column count (never 0): 0x00 is an OK if (first[0] === 0x00) { const c = new Cursor(first); c.u8(); return { affectedRows: c.lenenc(), insertId: c.lenenc() }; } const c = new Cursor(first); const count = c.lenenc(); const columns = payloads.slice(1, 1 + count).map(column); const rows: (string | null)[][] = []; for (const p of payloads.slice(2 + count)) { if (p[0] === 0xfe && p.length < 9) break; // the closing EOF if (p[0] === 0xff) return { error: errorOf(p) }; const r = new Cursor(p); if (!binary) { rows.push(columns.map(() => (r.b[r.at] === 0xfb ? (r.at++, null) : r.lenencStr()))); continue; } r.u8(); const bitmap = r.take(Math.floor((columns.length + 9) / 8)); rows.push(columns.map((col, i) => ((bitmap[Math.floor((i + 2) / 8)]! >> ((i + 2) % 8)) & 1 ? null : binaryValue(r, col.type, col.flags)))); } return { columns, rows }; } /** Sign in: the server's greeting, then the handshake response (mysql_native_password), following an auth switch. */ export async function mysqlSignIn(exchange: MysqlExchange, greeting: Uint8Array, user: string, password: string, database: string | null): Promise<{ ok: true } | { error: MysqlError }> { const g = new Cursor(packets(greeting)[0]!); g.u8(); g.nul(); g.u32(); const part1 = g.take(8); g.u8(); g.u16(); g.u8(); g.u16(); g.u16(); g.u8(); g.take(10); const part2 = g.take(12); const scramble = new Uint8Array([...part1, ...part2]); const token = nativePasswordToken(password, scramble); const body = [...new Uint8Array([CLIENT_CAPS & 0xff, (CLIENT_CAPS >> 8) & 0xff, (CLIENT_CAPS >> 16) & 0xff, (CLIENT_CAPS >> 24) & 0xff, 0, 0, 0, 1, 45]), ...new Array(23).fill(0), ...enc.encode(user), 0, token.length, ...token, ...(database ? [...enc.encode(database), 0] : [0]), ...enc.encode('mysql_native_password'), 0]; let reply = packets(await exchange(packet(1, Uint8Array.from(body))))[0]; if (reply?.[0] === 0xfe) { // the server asks for another plugin's answer: mysql_native_password with its scramble const c = new Cursor(reply); c.u8(); c.nul(); reply = packets(await exchange(packet(3, nativePasswordToken(password, c.take(20)))))[0]; } if (!reply || reply[0] === 0xff) return { error: reply ? errorOf(reply) : { errno: 2013, sqlstate: 'HY000', message: 'Lost connection to MySQL server during handshake' } }; return { ok: true }; } /** A text query (COM_QUERY): the first result of a script, as mysql_async reads it. */ export async function mysqlQuery(exchange: MysqlExchange, sql: string): Promise { return answer(packets(await exchange(packet(0, Uint8Array.from([0x03, ...enc.encode(sql)])))), false); } /** A prepared statement executed once with text-typed parameters (COM_STMT_PREPARE, EXECUTE, CLOSE), as Prisma sends a * parameterised query: binary parameters and rows. */ export async function mysqlExecute(exchange: MysqlExchange, sql: string, params: (string | null)[]): Promise { const prepared = packets(await exchange(packet(0, Uint8Array.from([0x16, ...enc.encode(sql)])))); if (prepared[0]?.[0] === 0xff) return { error: errorOf(prepared[0]) }; const c = new Cursor(prepared[0]!); c.u8(); const id = c.u32(); c.u16(); const count = c.u16(); const head = [0x17, id & 0xff, (id >> 8) & 0xff, (id >> 16) & 0xff, (id >>> 24) & 0xff, 0, 1, 0, 0, 0]; const values: number[] = []; if (count) { const bitmap = new Array(Math.floor((count + 7) / 8)).fill(0); params.forEach((v, i) => { if (v === null) bitmap[Math.floor(i / 8)] |= 1 << (i % 8); }); head.push(...bitmap, 1); for (let i = 0; i < count; i++) head.push(params[i] === null ? MysqlType.NULL : MysqlType.VAR_STRING, 0); for (const v of params) if (v !== null) { const b = enc.encode(v); values.push(...(b.length < 251 ? [b.length] : [0xfc, b.length & 0xff, b.length >> 8]), ...b); } } const result = answer(packets(await exchange(packet(0, Uint8Array.from([...head, ...values])))), true); await exchange(packet(0, Uint8Array.from([0x19, id & 0xff, (id >> 8) & 0xff, (id >> 16) & 0xff, (id >>> 24) & 0xff]))); return result; }