// THE KERNEL'S MYSQL WIRE (`@volter/world-core/mysql`): MySQL's client/server protocol as a TwinStream, so an unmodified // MySQL client (Prisma's engines over mysql_async, mysql2) connects to a twin as to a server. The kernel holds the // protocol, which every MySQL-speaking vendor shares; the pack holds what a statement means (it executes it in its own // engine over the tree) and whom it admits (it checks a password against what it stores). The command subset is what the // clients send, by citation (docs/contributing/architecture.md, "Other wires", the MySQL wire): protocol v10 with // mysql_native_password, COM_QUERY (text results, several per multi-statement script), COM_STMT_PREPARE / EXECUTE / // CLOSE / SEND_LONG_DATA / RESET (binary rows and parameters), COM_PING, COM_INIT_DB and COM_QUIT; any other command is // answered as MySQL answers an unknown one. // source: https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_basics.html import { createHash, randomBytes } from 'node:crypto'; import type { TwinStream, TwinStreamSink } from '../twin-fetch.ts'; /** A column as the pack's engine describes it: MySQL's column type code (`MysqlType`) and flags. */ export type MysqlColumn = { name: string; type: number; flags?: number; charset?: number; length?: number; decimals?: number; table?: string; orgTable?: string; orgName?: string; schema?: string; }; /** A statement's outcome: rows (each value as MySQL's text protocol carries it, or null), or a count, or MySQL's error. */ export type MysqlOutcome = | { columns: MysqlColumn[]; rows: (string | Uint8Array | null)[][]; warnings?: number } | { affectedRows: number; insertId?: number | bigint; warnings?: number; info?: string } | { error: MysqlError }; export type MysqlError = { errno: number; sqlstate: string; message: string }; export type MysqlStreamOptions = { /** The handshake's server version: the one the pack's engine reports for `VERSION()`. */ version: string; /** Admit `user` to `database` (null: none named) when `check` accepts what the pack stores for it: the password, or * MySQL's own stored form of it (`nativePasswordHash`, SHA1(SHA1(password)), as a server keeps it). */ connect(user: string, database: string | null, check: MysqlPasswordCheck): Promise<{ session: Session } | { error: MysqlError }>; /** Execute ONE statement (the kernel splits a script and binds parameters into the text) on the session. */ execute(session: Session, sql: string): Promise; /** Whether the session holds an open transaction (SERVER_STATUS_IN_TRANS). */ inTransaction(session: Session): boolean; /** Use another database on the session (COM_INIT_DB). */ useDatabase?(session: Session, database: string): Promise; /** The connection went away: roll back what it left open. */ close?(session: Session): void; }; /** MySQL's column type codes. */ export const MysqlType = { DECIMAL: 0x00, TINY: 0x01, SHORT: 0x02, LONG: 0x03, FLOAT: 0x04, DOUBLE: 0x05, NULL: 0x06, TIMESTAMP: 0x07, LONGLONG: 0x08, INT24: 0x09, DATE: 0x0a, TIME: 0x0b, DATETIME: 0x0c, YEAR: 0x0d, VARCHAR: 0x0f, BIT: 0x10, JSON: 0xf5, NEWDECIMAL: 0xf6, ENUM: 0xf7, SET: 0xf8, TINY_BLOB: 0xf9, MEDIUM_BLOB: 0xfa, LONG_BLOB: 0xfb, BLOB: 0xfc, VAR_STRING: 0xfd, STRING: 0xfe, GEOMETRY: 0xff, } as const; export const MysqlFlag = { NOT_NULL: 0x0001, PRI_KEY: 0x0002, UNIQUE_KEY: 0x0004, MULTIPLE_KEY: 0x0008, BLOB: 0x0010, UNSIGNED: 0x0020, BINARY: 0x0080, AUTO_INCREMENT: 0x0200 } as const; const CAP = { LONG_PASSWORD: 0x1, FOUND_ROWS: 0x2, LONG_FLAG: 0x4, CONNECT_WITH_DB: 0x8, PROTOCOL_41: 0x200, TRANSACTIONS: 0x2000, SECURE_CONNECTION: 0x8000, MULTI_STATEMENTS: 0x10000, MULTI_RESULTS: 0x20000, PS_MULTI_RESULTS: 0x40000, PLUGIN_AUTH: 0x80000, CONNECT_ATTRS: 0x100000, PLUGIN_AUTH_LENENC: 0x200000, } as const; // what this server offers: no TLS, no compression, no deprecated-EOF (classic EOF packets), no session tracking const SERVER_CAPS = CAP.LONG_PASSWORD | CAP.FOUND_ROWS | CAP.LONG_FLAG | CAP.CONNECT_WITH_DB | CAP.PROTOCOL_41 | CAP.TRANSACTIONS | CAP.SECURE_CONNECTION | CAP.MULTI_STATEMENTS | CAP.MULTI_RESULTS | CAP.PS_MULTI_RESULTS | CAP.PLUGIN_AUTH | CAP.CONNECT_ATTRS | CAP.PLUGIN_AUTH_LENENC; const STATUS = { IN_TRANS: 0x0001, AUTOCOMMIT: 0x0002, MORE_RESULTS: 0x0008 } as const; const COM = { QUIT: 0x01, INIT_DB: 0x02, QUERY: 0x03, PING: 0x0e, STMT_PREPARE: 0x16, STMT_EXECUTE: 0x17, STMT_SEND_LONG_DATA: 0x18, STMT_CLOSE: 0x19, STMT_RESET: 0x1a } as const; const UTF8MB4 = 45; // utf8mb4_general_ci const BINARY_CHARSET = 63; const NATIVE = 'mysql_native_password'; const MAX_PAYLOAD = 0xffffff; const enc = new TextEncoder(); const dec = new TextDecoder(); const sha1 = (...parts: Uint8Array[]): Uint8Array => { const h = createHash('sha1'); for (const p of parts) h.update(p); return new Uint8Array(h.digest()); }; /** Whether the client's mysql_native_password answer proves a password: from the password itself, or from MySQL's * stored form of it (hex SHA1(SHA1(password))), as a MySQL server checks it without holding the password. */ export type MysqlPasswordCheck = { password(password: string): boolean; storedHash(hex: string): boolean }; /** MySQL's stored form of a password for mysql_native_password: SHA1(SHA1(password)), hex. A pack keeps it when the * password is made, beside whatever else it keeps, so the wire can admit the password without the pack holding it. */ export function nativePasswordHash(password: string): string { return Array.from(sha1(sha1(enc.encode(password))), (b) => b.toString(16).padStart(2, '0')).join(''); } /** mysql_native_password's token for `password` against `scramble`: SHA1(pw) XOR SHA1(scramble + SHA1(SHA1(pw))). */ export function nativePasswordToken(password: string, scramble: Uint8Array): Uint8Array { if (!password) return new Uint8Array(0); const stage1 = sha1(enc.encode(password)); const mix = sha1(scramble, sha1(stage1)); return stage1.map((b, i) => b ^ mix[i]!); } // ── bytes ─────────────────────────────────────────────────────────────────────────────────────────────────────────── class Writer { private parts: number[] = []; u8(v: number): this { this.parts.push(v & 0xff); return this; } u16(v: number): this { return this.u8(v).u8(v >>> 8); } u24(v: number): this { return this.u8(v).u8(v >>> 8).u8(v >>> 16); } u32(v: number): this { return this.u16(v & 0xffff).u16(v >>> 16); } u64(v: bigint): this { const n = BigInt.asUintN(64, v); for (let i = 0n; i < 8n; i++) this.u8(Number((n >> (8n * i)) & 0xffn)); return this; } bytes(b: Uint8Array | number[]): this { for (const x of b) this.parts.push(x); return this; } str(s: string): this { return this.bytes(enc.encode(s)); } nul(s: string): this { return this.str(s).u8(0); } lenenc(v: number | bigint): this { const n = BigInt(v); if (n < 251n) return this.u8(Number(n)); if (n < 0x10000n) return this.u8(0xfc).u16(Number(n)); if (n < 0x1000000n) return this.u8(0xfd).u24(Number(n)); return this.u8(0xfe).u64(n); } lenencBytes(b: Uint8Array): this { return this.lenenc(b.length).bytes(b); } lenencStr(s: string): this { return this.lenencBytes(enc.encode(s)); } done(): Uint8Array { return Uint8Array.from(this.parts); } } class Reader { at = 0; constructor(readonly b: Uint8Array) {} left(): number { return this.b.length - this.at; } u8(): number { if (this.at >= this.b.length) throw new Error('packet too short'); return this.b[this.at++]!; } u16(): number { return this.u8() | (this.u8() << 8); } u24(): number { return this.u16() | (this.u8() << 16); } 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 { if (this.at + n > this.b.length) throw new Error('packet too short'); const out = this.b.subarray(this.at, this.at + n); this.at += n; return out; } rest(): Uint8Array { return this.take(this.left()); } nul(): string { const end = this.b.indexOf(0, this.at); const stop = end < 0 ? this.b.length : end; const s = dec.decode(this.b.subarray(this.at, stop)); this.at = end < 0 ? stop : stop + 1; return s; } lenenc(): bigint { const first = this.u8(); if (first < 0xfb) return BigInt(first); if (first === 0xfc) return BigInt(this.u16()); if (first === 0xfd) return BigInt(this.u24()); if (first === 0xfe) return this.u64(); throw new Error('bad length-encoded integer'); } lenencBytes(): Uint8Array { return this.take(Number(this.lenenc())); } } // ── SQL text: statements, placeholders and literals (lexical only: what a statement means is the pack's) ────────────── /** The offsets of `?` placeholders and `;` separators outside quotes, backticks and comments. */ function scan(sql: string): { placeholders: number[]; separators: number[] } { const placeholders: number[] = []; const separators: number[] = []; for (let i = 0; i < sql.length; i++) { const c = sql[i]!; if (c === "'" || c === '"' || c === '`') { for (i++; i < sql.length; i++) { if (sql[i] === '\\' && c !== '`') { i++; continue; } if (sql[i] === c) { if (sql[i + 1] === c) { i++; continue; } break; } } } else if (c === '#' || (c === '-' && sql[i + 1] === '-' && /\s/.test(sql[i + 2] ?? ' '))) { while (i < sql.length && sql[i] !== '\n') i++; } else if (c === '/' && sql[i + 1] === '*') { const end = sql.indexOf('*/', i + 2); i = end < 0 ? sql.length : end + 1; } else if (c === '?') placeholders.push(i); else if (c === ';') separators.push(i); } return { placeholders, separators }; } /** A multi-statement script's statements, empty ones dropped. */ export function splitStatements(sql: string): string[] { const { separators } = scan(sql); const out: string[] = []; let from = 0; for (const at of [...separators, sql.length]) { const s = sql.slice(from, at).trim(); if (s) out.push(s); from = at + 1; } return out; } export function countPlaceholders(sql: string): number { return scan(sql).placeholders.length; } /** A bound parameter: an integer, a float, text, bytes (a BLOB parameter, or text that is not UTF-8), a date or time. */ export type MysqlParam = null | bigint | number | string | Uint8Array | { date: string }; /** A parameter as a MySQL literal, written as PlanetScale's own driver formats one, so an engine that executes text * reads both wires' statements alike. */ // source: https://github.com/planetscale/database-js/blob/v1.19.0/src/sanitization.ts "const re = /[\0\b\n\r\t\x1a\\"']/g" // source: https://github.com/planetscale/database-js/blob/v1.19.0/src/text.ts "return `x'${digits.join('')}'`" function literal(v: MysqlParam): string { if (v === null) return 'null'; if (typeof v === 'bigint' || typeof v === 'number') return String(v); if (v instanceof Uint8Array) return `x'${Array.from(v, (b) => b.toString(16).padStart(2, '0')).join('')}'`; if (typeof v === 'object') return quote(v.date); return quote(v); } const ESCAPES: Record = { '"': '\\"', "'": "\\'", '\n': '\\n', '\r': '\\r', '\t': '\\t', '\\': '\\\\', '\0': '\\0', '\b': '\\b', '\x1a': '\\Z' }; function quote(text: string): string { return `'${text.replace(/[\0\b\n\r\t\x1a\\"']/g, (c) => ESCAPES[c]!)}'`; } /** `sql` with each `?` placeholder replaced by its parameter's literal. */ export function bindParameters(sql: string, params: MysqlParam[]): string { const { placeholders } = scan(sql); if (placeholders.length !== params.length) throw new Error(`the statement has ${placeholders.length} placeholders and ${params.length} parameters`); let out = ''; let from = 0; placeholders.forEach((at, i) => { out += sql.slice(from, at) + literal(params[i]!); from = at + 1; }); return out + sql.slice(from); } // ── binary protocol values ────────────────────────────────────────────────────────────────────────────────────────── const pad = (n: number, w = 2) => String(n).padStart(w, '0'); function readParam(r: Reader, type: number, unsigned: boolean): MysqlParam { switch (type) { case MysqlType.NULL: return null; case MysqlType.TINY: { const v = r.u8(); return BigInt(unsigned ? v : (v << 24) >> 24); } case MysqlType.SHORT: case MysqlType.YEAR: { const v = r.u16(); return BigInt(unsigned ? v : (v << 16) >> 16); } case MysqlType.LONG: case MysqlType.INT24: { const v = r.u32(); return BigInt(unsigned ? v : v | 0); } case MysqlType.LONGLONG: { const v = r.u64(); return unsigned ? v : BigInt.asIntN(64, v); } case MysqlType.FLOAT: { const b = r.take(4); return new DataView(b.buffer, b.byteOffset, 4).getFloat32(0, true); } case MysqlType.DOUBLE: { const b = r.take(8); return new DataView(b.buffer, b.byteOffset, 8).getFloat64(0, true); } case MysqlType.DATE: case MysqlType.DATETIME: case MysqlType.TIMESTAMP: { const len = r.u8(); if (len === 0) return { date: type === MysqlType.DATE ? '0000-00-00' : '0000-00-00 00:00:00' }; const y = r.u16(), m = r.u8(), d = r.u8(); const [h, i, s] = len >= 7 ? [r.u8(), r.u8(), r.u8()] : [0, 0, 0]; const us = len >= 11 ? r.u32() : 0; const day = `${pad(y, 4)}-${pad(m)}-${pad(d)}`; return { date: type === MysqlType.DATE ? day : `${day} ${pad(h)}:${pad(i)}:${pad(s)}${us ? `.${pad(us, 6)}` : ''}` }; } case MysqlType.TIME: { const len = r.u8(); if (len === 0) return { date: '00:00:00' }; const neg = r.u8(), days = r.u32(), h = r.u8(), i = r.u8(), s = r.u8(); const us = len >= 12 ? r.u32() : 0; return { date: `${neg ? '-' : ''}${pad(days * 24 + h)}:${pad(i)}:${pad(s)}${us ? `.${pad(us, 6)}` : ''}` }; } case MysqlType.TINY_BLOB: case MysqlType.MEDIUM_BLOB: case MysqlType.LONG_BLOB: case MysqlType.BLOB: case MysqlType.GEOMETRY: return r.lenencBytes().slice(); default: { // mysql_async sends text and bytes alike as VAR_STRING: text that is UTF-8 is a string (MySQL's string comparison and // collation apply), anything else the bytes it is const bytes = r.lenencBytes().slice(); try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { return bytes; } } } } /** A text-protocol value in a column's binary encoding. */ function writeBinaryValue(w: Writer, column: MysqlColumn, value: string | Uint8Array): void { const text = typeof value === 'string' ? value : dec.decode(value); const unsigned = ((column.flags ?? 0) & MysqlFlag.UNSIGNED) !== 0; switch (column.type) { case MysqlType.TINY: w.u8(Number(BigInt(text))); return; case MysqlType.SHORT: case MysqlType.YEAR: w.u16(Number(BigInt(text))); return; case MysqlType.LONG: case MysqlType.INT24: w.u32(Number(BigInt.asUintN(32, BigInt(text)))); return; case MysqlType.LONGLONG: w.u64(unsigned ? BigInt(text) : BigInt.asUintN(64, BigInt(text))); return; case MysqlType.FLOAT: { const b = new Uint8Array(4); new DataView(b.buffer).setFloat32(0, Number(text), true); w.bytes(b); return; } case MysqlType.DOUBLE: { const b = new Uint8Array(8); new DataView(b.buffer).setFloat64(0, Number(text), true); w.bytes(b); return; } case MysqlType.DATE: case MysqlType.DATETIME: case MysqlType.TIMESTAMP: { const m = /^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?)?$/.exec(text); if (!m) { w.u8(0); return; } const [y, mo, d, h, i, s] = [m[1], m[2], m[3], m[4] ?? '0', m[5] ?? '0', m[6] ?? '0'].map(Number) as number[]; const us = m[7] ? Number(m[7].padEnd(6, '0')) : 0; if (!y && !mo && !d && !h && !i && !s && !us) { w.u8(0); return; } if (us) { w.u8(11).u16(y!).u8(mo!).u8(d!).u8(h!).u8(i!).u8(s!).u32(us); return; } if (h || i || s) { w.u8(7).u16(y!).u8(mo!).u8(d!).u8(h!).u8(i!).u8(s!); return; } w.u8(4).u16(y!).u8(mo!).u8(d!); return; } case MysqlType.TIME: { const m = /^(-)?(\d+):(\d{2}):(\d{2})(?:\.(\d{1,6}))?$/.exec(text); if (!m) { w.u8(0); return; } const hours = Number(m[2]); const us = m[5] ? Number(m[5].padEnd(6, '0')) : 0; const days = Math.floor(hours / 24); if (!hours && m[3] === '00' && m[4] === '00' && !us) { w.u8(0); return; } w.u8(us ? 12 : 8).u8(m[1] ? 1 : 0).u32(days).u8(hours % 24).u8(Number(m[3])).u8(Number(m[4])); if (us) w.u32(us); return; } default: w.lenencBytes(typeof value === 'string' ? enc.encode(value) : value); } } // ── packets ───────────────────────────────────────────────────────────────────────────────────────────────────────── function columnDefinition(c: MysqlColumn): Uint8Array { const binary = c.charset === BINARY_CHARSET; return new Writer().lenencStr('def').lenencStr(c.schema ?? '').lenencStr(c.table ?? '').lenencStr(c.orgTable ?? c.table ?? '') .lenencStr(c.name).lenencStr(c.orgName ?? c.name).u8(0x0c).u16(c.charset ?? (binary ? BINARY_CHARSET : UTF8MB4)) .u32(c.length ?? 0).u8(c.type).u16(c.flags ?? 0).u8(c.decimals ?? 0).u16(0).done(); } const errPacket = (e: MysqlError): Uint8Array => new Writer().u8(0xff).u16(e.errno).str('#').str((e.sqlstate + '00000').slice(0, 5)).str(e.message).done(); const eofPacket = (status: number, warnings = 0): Uint8Array => new Writer().u8(0xfe).u16(warnings).u16(status).done(); const okPacket = (affected: number | bigint, insertId: number | bigint, status: number, warnings = 0, info = ''): Uint8Array => new Writer().u8(0x00).lenenc(affected).lenenc(insertId).u16(status).u16(warnings).str(info).done(); const unknownCommand: MysqlError = { errno: 1047, sqlstate: '08S01', message: 'Unknown command' }; type Prepared = { sql: string; params: number; types: number[]; long: Map }; /** A MySQL server as a TwinStream: the protocol here, the meaning in `options`. */ export function createMysqlStream(options: MysqlStreamOptions): TwinStream { let nextConnection = 0; return (sink: TwinStreamSink) => { const connectionId = ++nextConnection; const scramble = new Uint8Array(randomBytes(20)).map((b) => (b & 0x7f) || 0x41); // printable, never NUL let seq = 0; let buffer = new Uint8Array(0); let phase: 'handshake' | 'switch' | 'ready' | 'closed' = 'handshake'; let clientCaps = 0; let pending: { user: string; database: string | null } | null = null; let session: Session | null = null; const statements = new Map(); let nextStatement = 0; let chain: Promise = Promise.resolve(); const send = (payload: Uint8Array): void => { // a payload of 2^24-1 bytes or more is split, ending with a shorter packet (possibly empty) let at = 0; do { const part = payload.subarray(at, at + MAX_PAYLOAD); sink.write(Uint8Array.from([...new Writer().u24(part.length).u8(seq).done(), ...part])); seq = (seq + 1) & 0xff; at += part.length; if (part.length < MAX_PAYLOAD) break; } while (true); }; const status = (more = false): number => STATUS.AUTOCOMMIT | (session && options.inTransaction(session) ? STATUS.IN_TRANS : 0) | (more ? STATUS.MORE_RESULTS : 0); const fail = (e: MysqlError): void => send(errPacket(e)); // the greeting: protocol v10, the scramble, mysql_native_password send(new Writer().u8(10).nul(options.version).u32(connectionId).bytes(scramble.subarray(0, 8)).u8(0) .u16(SERVER_CAPS & 0xffff).u8(UTF8MB4).u16(STATUS.AUTOCOMMIT).u16(SERVER_CAPS >>> 16).u8(21).bytes(new Array(10).fill(0)) .bytes(scramble.subarray(8)).u8(0).nul(NATIVE).done()); const admit = async (token: Uint8Array): Promise => { const { user, database } = pending!; const check: MysqlPasswordCheck = { password: (password) => { const want = nativePasswordToken(password, scramble); return want.length === token.length && want.every((b, i) => b === token[i]); }, // SHA1(token XOR SHA1(scramble + stored)) is SHA1(SHA1(password)) exactly when the client knew the password storedHash: (hex) => { if (!/^[0-9a-f]{40}$/i.test(hex)) return false; if (token.length === 0) return false; // an empty answer proves only an empty password, which a stored hash never is if (token.length !== 20) return false; const stored = Uint8Array.from(hex.match(/../g)!.map((h) => parseInt(h, 16))); const mix = sha1(scramble, stored); const stage1 = token.map((b, i) => b ^ mix[i]!); return sha1(stage1).every((b, i) => b === stored[i]); }, }; const answer = await options.connect(user, database, check); if ('error' in answer) { fail(answer.error); phase = 'closed'; sink.end(); return; } session = answer.session; phase = 'ready'; send(okPacket(0, 0, status())); }; const handshakeResponse = async (payload: Uint8Array): Promise => { const r = new Reader(payload); clientCaps = r.u32(); r.u32(); r.u8(); r.take(23); const user = r.nul(); let token: Uint8Array; if (clientCaps & CAP.PLUGIN_AUTH_LENENC) token = r.lenencBytes(); else if (clientCaps & CAP.SECURE_CONNECTION) token = r.take(r.u8()); else token = enc.encode(r.nul()); const database = (clientCaps & CAP.CONNECT_WITH_DB) && r.left() ? r.nul() || null : null; const plugin = (clientCaps & CAP.PLUGIN_AUTH) && r.left() ? r.nul() : NATIVE; pending = { user, database }; if (plugin !== NATIVE) { // the client answered for another plugin: ask it to switch to mysql_native_password with the same scramble phase = 'switch'; send(new Writer().u8(0xfe).nul(NATIVE).bytes(scramble).u8(0).done()); return; } await admit(token.slice()); }; const resultSet = (outcome: MysqlOutcome, binary: boolean, more: boolean): void => { if ('error' in outcome) { fail(outcome.error); return; } if (!('columns' in outcome)) { send(okPacket(outcome.affectedRows, outcome.insertId ?? 0, status(more), outcome.warnings ?? 0, outcome.info ?? '')); return; } send(new Writer().lenenc(outcome.columns.length).done()); for (const c of outcome.columns) send(columnDefinition(c)); send(eofPacket(status(more))); for (const row of outcome.rows) { const w = new Writer(); if (!binary) { for (const v of row) { if (v === null) w.u8(0xfb); else if (typeof v === 'string') w.lenencStr(v); else w.lenencBytes(v); } } else { w.u8(0x00); const bitmap = new Array(Math.floor((outcome.columns.length + 7 + 2) / 8)).fill(0); row.forEach((v, i) => { if (v === null) bitmap[Math.floor((i + 2) / 8)] |= 1 << ((i + 2) % 8); }); w.bytes(bitmap); row.forEach((v, i) => { if (v !== null) writeBinaryValue(w, outcome.columns[i]!, v); }); } send(w.done()); } send(eofPacket(status(more), outcome.warnings ?? 0)); }; const query = async (sql: string): Promise => { const parts = clientCaps & CAP.MULTI_STATEMENTS ? splitStatements(sql) : [sql.trim()]; if (!parts.length) { fail({ errno: 1065, sqlstate: '42000', message: 'Query was empty' }); return; } for (let i = 0; i < parts.length; i++) { const outcome = await options.execute(session!, parts[i]!); const last = i === parts.length - 1 || 'error' in outcome; resultSet(outcome, false, !last); if ('error' in outcome) return; // a script stops at its first error, as MySQL's does } }; const prepare = (sql: string): void => { const params = countPlaceholders(sql); const id = ++nextStatement; statements.set(id, { sql, params, types: [], long: new Map() }); // no result columns are named at prepare: the execute's result set carries them send(new Writer().u8(0x00).u32(id).u16(0).u16(params).u8(0).u16(0).done()); if (params) { for (let i = 0; i < params; i++) send(columnDefinition({ name: '?', type: MysqlType.VAR_STRING, charset: BINARY_CHARSET })); send(eofPacket(status())); } }; const execute = async (r: Reader): Promise => { const id = r.u32(); r.u8(); r.u32(); // flags (no cursors), iteration count const stmt = statements.get(id); if (!stmt) { fail({ errno: 1243, sqlstate: 'HY000', message: `Unknown prepared statement handler (${id}) given to mysqld_stmt_execute` }); return; } const values: MysqlParam[] = []; if (stmt.params) { const bitmap = r.take(Math.floor((stmt.params + 7) / 8)); if (r.u8() === 1) { stmt.types = []; for (let i = 0; i < stmt.params; i++) stmt.types.push(r.u16()); } for (let i = 0; i < stmt.params; i++) { const long = stmt.long.get(i); if (long) { values.push(Uint8Array.from(long)); continue; } if (bitmap[Math.floor(i / 8)]! & (1 << (i % 8))) { values.push(null); continue; } const t = stmt.types[i] ?? MysqlType.VAR_STRING; values.push(readParam(r, t & 0xff, (t & 0x8000) !== 0)); } stmt.long.clear(); } let sql: string; try { sql = bindParameters(stmt.sql, values); } catch (e) { fail({ errno: 1210, sqlstate: 'HY000', message: `Incorrect arguments to mysqld_stmt_execute: ${(e as Error).message}` }); return; } resultSet(await options.execute(session!, sql), true, false); }; const command = async (payload: Uint8Array): Promise => { seq = 1; // a command's packets begin a new sequence; the client's was 0 const r = new Reader(payload); const code = r.u8(); switch (code) { case COM.QUIT: phase = 'closed'; if (session) options.close?.(session); sink.end(); return; case COM.PING: send(okPacket(0, 0, status())); return; case COM.QUERY: await query(dec.decode(r.rest())); return; case COM.INIT_DB: { const err = options.useDatabase ? await options.useDatabase(session!, dec.decode(r.rest())) : unknownCommand; if (err) fail(err); else send(okPacket(0, 0, status())); return; } case COM.STMT_PREPARE: prepare(dec.decode(r.rest())); return; case COM.STMT_EXECUTE: await execute(r); return; case COM.STMT_SEND_LONG_DATA: { // no reply const stmt = statements.get(r.u32()); const param = r.u16(); if (stmt) stmt.long.set(param, [...(stmt.long.get(param) ?? []), ...r.rest()]); return; } case COM.STMT_CLOSE: statements.delete(r.u32()); return; // no reply case COM.STMT_RESET: { const stmt = statements.get(r.u32()); stmt?.long.clear(); send(okPacket(0, 0, status())); return; } default: fail(unknownCommand); } }; // whole packets out of the bytes, a split payload rejoined (2^24-1-byte parts end with a shorter one) let assembling: number[] | null = null; const packets = (): Uint8Array[] => { const out: Uint8Array[] = []; while (buffer.length >= 4) { const len = buffer[0]! | (buffer[1]! << 8) | (buffer[2]! << 16); if (buffer.length < 4 + len) break; const part = buffer.subarray(4, 4 + len); buffer = buffer.slice(4 + len); if (len === MAX_PAYLOAD) { assembling = [...(assembling ?? []), ...part]; continue; } out.push(assembling ? Uint8Array.from([...assembling, ...part]) : part.slice()); assembling = null; } return out; }; const handle = async (payload: Uint8Array): Promise => { if (phase === 'closed') return; try { if (phase === 'handshake') { seq = 2; await handshakeResponse(payload); return; } if (phase === 'switch') { seq = 4; await admit(payload.slice()); return; } await command(payload); } catch (e) { fail({ errno: 1105, sqlstate: 'HY000', message: (e as Error).message }); } }; return { data(chunk) { if (phase === 'closed') return; const joined = new Uint8Array(buffer.length + chunk.length); joined.set(buffer); joined.set(chunk, buffer.length); buffer = joined; for (const p of packets()) chain = chain.then(() => handle(p)); }, settled: () => chain, close: () => { if (phase !== 'closed' && session) options.close?.(session); phase = 'closed'; }, }; }; }