@nextlyhq/adapter-mysql 0.0.2-alpha.68 → 0.0.2-alpha.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":["DrizzleAdapter","mysql","checkDialectVersion","acceptsForShare","isApplicationError","createDatabaseError","drizzle","and","eq","getColumns","getTableConfig","rows","isDatabaseError"],"mappings":";;;;;;;;;;;;;;;AA8IA,eAAe,cAAA,CACb,YACA,OAAA,EACkB;AAClB,EAAA,IAAI,OAAA,KAAY,MAAM,OAAO,IAAA;AAC7B,EAAA,IAAI,OAAA,CAAQ,eAAA,KAAoB,IAAA,EAAM,OAAO,KAAA;AAC7C,EAAA,IAAI;AAEF,IAAA,MAAM,UAAA,CAAW,KAAA;AAAA,MACf,CAAA,uCAAA,EAA0C,QAAQ,eAAe,CAAA;AAAA,KACnE;AACA,IAAA,OAAO,IAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AASA,eAAe,2BAAA,CACb,UAAA,EACA,cAAA,EACA,OAAA,EACe;AACf,EAAA,IAAI,CAAC,cAAA,IAAmB,MAAM,cAAA,CAAe,UAAA,EAAY,OAAO,CAAA,EAAI;AAClE,IAAA,UAAA,CAAW,OAAA,EAAQ;AAAA,EACrB,CAAA,MAAO;AACL,IAAA,UAAA,CAAW,OAAA,EAAQ;AAAA,EACrB;AACF;AA+BO,IAAM,OAAA,GAAU;AAKvB,IAAM,mBAAA,GAAsB;AAAA,EAE1B,GAAA,EAAK,EAAA;AAAA,EACL,aAAA,EAAe,GAAA;AAAA,EACf,mBAAA,EAAqB;AACvB,CAAA;AAOA,IAAM,iBAAA,GAAuD;AAAA;AAAA,EAE3D,IAAA,EAAM,kBAAA;AAAA;AAAA,EACN,IAAA,EAAM,kBAAA;AAAA;AAAA,EACN,IAAA,EAAM,kBAAA;AAAA;AAAA,EACN,IAAA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AA,CAAW,IAAA;AAAA,MACjB,SAAS,UAAA,CAAW,OAAA,CAAQ,GAAA,CAAI,CAAA,MAAA,KAAU,OAAO,IAAI;AAAA,KACvD,CAAE,CAAA;AAAA,IACF,GAAG,MAAA,CAAO,OAAA,CACP,MAAA,CAAO,CAAA,KAAA,KAAS,KAAA,CAAM,MAAA,CAAO,MAAA,KAAW,IAAI,CAAA,CAC5C,GAAA,CAAI,CAAA,KAAA,MAAU;AAAA,MACb,IAAA,EAAM,MAAM,MAAA,CAAO,IAAA;AAAA,MACnB,OAAA,EAAU,KAAA,CAAM,MAAA,CAAO,OAAA,CAA+B,GAAA;AAAA,QACpD,YAAU,MAAA,CAAO;AAAA;AACnB,KACF,CAAE;AAAA,GACN;AACA,EAAA,MAAM,IAAA,GAAO,EAAE,OAAA,EAAS,MAAA,EAAO;AAC/B,EAAA,UAAA,CAAW,GAAA,CAAI,UAAU,IAAI,CAAA;AAC7B,EAAA,OAAO,IAAA;AACT;AAgCO,SAAS,mBAAmB,MAAA,EAA0C;AAC3E,EAAA,OAAO,IAAI,aAAa,MAAM,CAAA;AAChC;AAgBO,SAAS,eAAe,KAAA,EAAuC;AACpE,EAAA,OAAO,KAAA,YAAiB,YAAA;AAC1B","file":"index.cjs","sourcesContent":["/**\n * @nextlyhq/adapter-mysql\n *\n * MySQL database adapter for Nextly.\n * Extends DrizzleAdapter from @nextlyhq/adapter-drizzle to provide MySQL-specific functionality.\n *\n * @remarks\n * This adapter uses the mysql2 package for database connectivity and provides:\n * - Connection pooling via mysql2 Pool\n * - Full transaction support with isolation levels\n * - CRUD operations with workarounds for missing RETURNING clause\n * - MySQL-specific error classification\n * - Automatic retry for deadlocks (error 1213)\n *\n * @example\n * ```typescript\n * import { createMySqlAdapter } from '@nextlyhq/adapter-mysql';\n *\n * const adapter = createMySqlAdapter({\n * url: process.env.DATABASE_URL!,\n * });\n *\n * await adapter.connect();\n *\n * // Query data\n * const users = await adapter.select('users', {\n * where: { and: [{ column: 'status', op: '=', value: 'active' }] },\n * limit: 10,\n * });\n *\n * await adapter.disconnect();\n * ```\n *\n * @packageDocumentation\n */\n\nimport { DrizzleAdapter } from \"@nextlyhq/adapter-drizzle\";\n// F17: connect-time DB version check shared across all adapters.\nimport {\n createDatabaseError,\n isDatabaseError,\n type MySqlAdapterConfig,\n type DatabaseCapabilities,\n type PoolStats,\n type TransactionContext,\n type TransactionOptions,\n type SqlParam,\n type WhereClause,\n type WhereCondition,\n type WhereOperator,\n type SelectOptions,\n type InsertOptions,\n type UpdateOptions,\n type DeleteOptions,\n type UpsertOptions,\n type OrderBySpec,\n type JoinSpec,\n type DatabaseError,\n type DatabaseErrorKind,\n type BaseAdapterConfig,\n type AdapterLogger,\n type PoolConfig,\n type SslConfig,\n isApplicationError,\n} from \"@nextlyhq/adapter-drizzle/types\";\nimport {\n acceptsForShare,\n checkDialectVersion,\n} from \"@nextlyhq/adapter-drizzle/version-check\";\nimport { and, eq, getColumns } from \"drizzle-orm\";\nimport type { AnyRelations, Column, SQL } from \"drizzle-orm\";\nimport { getTableConfig, type MySqlTable } from \"drizzle-orm/mysql-core\";\nimport { drizzle, type MySql2Database } from \"drizzle-orm/mysql2\";\nimport type {\n Pool as CallbackPool,\n Connection as CallbackConnection,\n} from \"mysql2\";\nimport mysql from \"mysql2/promise\";\nimport type {\n PoolOptions,\n RowDataPacket,\n ResultSetHeader,\n} from \"mysql2/promise\";\n\n// mysql2 type definitions use mixin patterns that TypeScript struggles with.\n// We define explicit interfaces for the methods we need.\n\n/**\n * Query result type - either rows or a result header\n */\ntype QueryResult = RowDataPacket[] | RowDataPacket[][] | ResultSetHeader;\n\n/**\n * Queryable interface for mysql2 connections\n */\ninterface Queryable {\n query<T extends QueryResult>(sql: string): Promise<[T, unknown]>;\n query<T extends QueryResult>(\n sql: string,\n values: unknown[]\n ): Promise<[T, unknown]>;\n}\n\n/**\n * mysql2 Pool interface with query method\n */\ninterface Pool extends Queryable {\n getConnection(): Promise<PoolConnection>;\n end(): Promise<void>;\n pool?: {\n _allConnections?: { length: number };\n _freeConnections?: { length: number };\n _connectionQueue?: { length: number };\n };\n}\n\n/**\n * mysql2 PoolConnection interface with query and release methods\n */\ninterface PoolConnection extends Queryable {\n /** Returns the connection to the pool, for the next request to use. */\n release(): void;\n /** Closes the connection and removes it from the pool. */\n destroy(): void;\n}\n\n/**\n * What a transaction changed on its connection's session, to put back before\n * the connection returns to the pool; null when it changed nothing.\n *\n * MySQL has no transaction-scoped form of `innodb_lock_wait_timeout`: a\n * `SET SESSION` outlives the transaction, and the pooled connection would\n * carry one transaction's timeout into every later query handed it.\n * `lockWaitTimeout` is the session's value from before the change, or null\n * when it could not be read, and then the connection cannot be put back.\n */\ntype SessionRestore = { lockWaitTimeout: number | null } | null;\n\n/**\n * Puts back what a transaction changed on its connection's session. False\n * when that could not be done, and the connection must not be pooled.\n */\nasync function restoreSession(\n connection: PoolConnection,\n restore: SessionRestore\n): Promise<boolean> {\n if (restore === null) return true;\n if (restore.lockWaitTimeout === null) return false;\n try {\n // An integer read from the server, never caller input.\n await connection.query(\n `SET SESSION innodb_lock_wait_timeout = ${restore.lockWaitTimeout}`\n );\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Ends a transaction's hold on its connection: back to the pool once its\n * session is as the transaction found it, or closed when it is not. A\n * connection whose ROLLBACK failed (`rollbackFailed`) may still be inside\n * the transaction, and the next request handed it would write into a\n * transaction nobody commits.\n */\nasync function returnTransactionConnection(\n connection: PoolConnection,\n rollbackFailed: boolean,\n restore: SessionRestore\n): Promise<void> {\n if (!rollbackFailed && (await restoreSession(connection, restore))) {\n connection.release();\n } else {\n connection.destroy();\n }\n}\n\n// Re-export types for convenience\nexport type {\n MySqlAdapterConfig,\n DatabaseCapabilities,\n PoolStats,\n TransactionContext,\n TransactionOptions,\n SqlParam,\n WhereClause,\n WhereCondition,\n WhereOperator,\n SelectOptions,\n InsertOptions,\n UpdateOptions,\n DeleteOptions,\n UpsertOptions,\n OrderBySpec,\n JoinSpec,\n DatabaseError,\n DatabaseErrorKind,\n BaseAdapterConfig,\n AdapterLogger,\n PoolConfig,\n SslConfig,\n};\n\n/**\n * Package version\n */\nexport const VERSION = \"0.1.0\";\n\n/**\n * Default pool configuration values.\n */\nconst DEFAULT_POOL_CONFIG = {\n min: 2,\n max: 10,\n idleTimeoutMs: 30000,\n connectionTimeoutMs: 10000,\n};\n\n/**\n * MySQL error codes mapping to DatabaseErrorKind.\n *\n * @see https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html\n */\nconst MYSQL_ERROR_CODES: Record<number, DatabaseErrorKind> = {\n // Unique/Duplicate key violations\n 1022: \"unique_violation\", // ER_DUP_KEY\n 1062: \"unique_violation\", // ER_DUP_ENTRY\n 1169: \"unique_violation\", // ER_DUP_UNIQUE\n 1586: \"unique_violation\", // ER_DUP_ENTRY_WITH_KEY_NAME\n\n // Foreign key violations\n 1216: \"foreign_key_violation\", // ER_NO_REFERENCED_ROW\n 1217: \"foreign_key_violation\", // ER_ROW_IS_REFERENCED\n 1451: \"foreign_key_violation\", // ER_ROW_IS_REFERENCED_2\n 1452: \"foreign_key_violation\", // ER_NO_REFERENCED_ROW_2\n\n // Not null violations\n 1048: \"not_null_violation\", // ER_BAD_NULL_ERROR\n 1364: \"not_null_violation\", // ER_NO_DEFAULT_FOR_FIELD\n\n // Check constraint violations (MySQL 8.0.16+)\n 3819: \"check_violation\", // ER_CHECK_CONSTRAINT_VIOLATED\n\n // Deadlock\n 1213: \"deadlock\", // ER_LOCK_DEADLOCK\n\n // Timeout\n 1205: \"timeout\", // ER_LOCK_WAIT_TIMEOUT\n\n // Connection errors\n 1040: \"connection\", // ER_CON_COUNT_ERROR - Too many connections\n 1042: \"connection\", // ER_BAD_HOST_ERROR\n 1043: \"connection\", // ER_HANDSHAKE_ERROR\n 1044: \"connection\", // ER_DBACCESS_DENIED_ERROR\n 1045: \"connection\", // ER_ACCESS_DENIED_ERROR\n 1129: \"connection\", // ER_HOST_IS_BLOCKED\n 1130: \"connection\", // ER_HOST_NOT_PRIVILEGED\n 2002: \"connection\", // CR_CONNECTION_ERROR\n 2003: \"connection\", // CR_CONN_HOST_ERROR\n 2006: \"connection\", // CR_SERVER_GONE_ERROR\n 2013: \"connection\", // CR_SERVER_LOST\n\n // Query errors\n 1064: \"query\", // ER_PARSE_ERROR\n 1146: \"query\", // ER_NO_SUCH_TABLE\n 1054: \"query\", // ER_BAD_FIELD_ERROR\n};\n\n/**\n * Delay helper for retry logic.\n */\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * MySQL database adapter for Nextly.\n *\n * Extends the base DrizzleAdapter to provide MySQL-specific functionality\n * using the mysql2 package.\n *\n * @remarks\n * MySQL has some limitations compared to PostgreSQL:\n * - No native RETURNING clause (requires INSERT then SELECT)\n * - No native ILIKE (uses LOWER() LIKE workaround)\n * - No native JSONB (uses JSON type)\n * - No array types\n * - Savepoints disabled for safety (MySQL has nested transaction quirks)\n *\n * @example\n * ```typescript\n * const adapter = new MySqlAdapter({\n * url: 'mysql://user:pass@localhost:3306/mydb',\n * pool: { max: 20 },\n * });\n *\n * await adapter.connect();\n * ```\n */\nexport class MySqlAdapter extends DrizzleAdapter {\n // getDrizzle memoization: drizzle v1's constructor builds a relational\n // query builder per table in the relations config (~40 tables), and the\n // service layer resolves an instance on every db access — construct once\n // per relations object (identity-stable: the schema registry caches it\n // and hands out a NEW object on invalidation, which naturally misses\n // this cache and produces a fresh instance).\n private drizzleByRelations = new WeakMap<AnyRelations, unknown>();\n private drizzleBare: unknown;\n\n /**\n * The database dialect - always 'mysql' for this adapter.\n */\n readonly dialect = \"mysql\" as const;\n\n /**\n * Adapter configuration.\n */\n protected readonly config: MySqlAdapterConfig;\n\n /**\n * Connection pool instance.\n */\n private pool: Pool | null = null;\n\n /**\n * Connection state flag.\n */\n private connected = false;\n\n /**\n * Whether the server accepts `SELECT ... FOR SHARE`, read from its version\n * string at connect. Undefined until then, which callers treat as not known.\n */\n private sharedRowLock: boolean | undefined;\n\n /**\n * Creates a new MySQL adapter instance.\n *\n * @param config - Adapter configuration\n */\n constructor(config: MySqlAdapterConfig) {\n super();\n this.config = config;\n }\n\n /**\n * Connect to the MySQL database.\n * Creates a connection pool using mysql2.\n *\n * @remarks\n * This method initializes the connection pool and verifies connectivity\n * by executing a simple query. It is idempotent - calling it multiple\n * times will not create multiple pools.\n *\n * @throws {DatabaseError} If connection fails\n */\n async connect(): Promise<void> {\n if (this.connected && this.pool) {\n return;\n }\n\n try {\n const poolConfig = this.buildPoolConfig();\n // Cast to our Pool interface - mysql2's mixin types don't resolve properly\n this.pool = mysql.createPool(poolConfig) as unknown as Pool;\n\n // Verify connection with smoke test, then check dialect version.\n // Why: F17 hard-fails at connect on real MySQL <8.0 (no variant\n // token detected). Recognized variants (MariaDB, TiDB, Aurora,\n // PlanetScale, Vitess) log a warning via the adapter logger and\n // proceed. Truly unparseable strings hard-fail so users see the\n // issue at boot rather than mid-apply.\n const connection = await this.pool.getConnection();\n try {\n await connection.query(\"SELECT 1\");\n const { variant } = await checkDialectVersion(connection, \"mysql\", {\n // Why: route variant warnings through the adapter's logger so\n // users see a single, consistent log surface.\n onWarning: msg => this.config.logger?.warn?.(msg),\n });\n // MariaDB and TiDB connect through this adapter too, and reject\n // `FOR SHARE`; the capability tells callers which lock they can take.\n this.sharedRowLock = acceptsForShare(variant);\n this.connected = true;\n\n if (this.config.logger?.info) {\n this.config.logger.info(\"MySQL connection established\", {\n host: this.config.host ?? \"from URL\",\n database: this.config.database ?? \"from URL\",\n });\n }\n } finally {\n connection.release();\n }\n } catch (error) {\n // Clean up on failure\n if (this.pool) {\n await this.pool.end().catch(() => {});\n this.pool = null;\n }\n throw this.classifyError(error);\n }\n }\n\n /**\n * Disconnect from the MySQL database.\n * Gracefully closes the connection pool.\n *\n * @remarks\n * This method is idempotent - calling it multiple times is safe.\n * It waits for all connections to be released before shutting down.\n */\n async disconnect(): Promise<void> {\n // Detach the pool FIRST, then drop the memoized drizzle instances —\n // this closes the repopulation window where a concurrent getDrizzle()\n // call during the (async) pool.end() could cache an instance wrapping\n // the closing pool.\n const pool = this.pool;\n this.pool = null;\n this.drizzleBare = undefined;\n this.drizzleByRelations = new WeakMap();\n if (!pool) {\n return;\n }\n\n try {\n await pool.end();\n\n if (this.config.logger?.info) {\n this.config.logger.info(\"MySQL connection closed\");\n }\n } finally {\n this.connected = false;\n }\n }\n\n /**\n * Check if connected to the database.\n */\n isConnected(): boolean {\n return this.connected && this.pool !== null;\n }\n\n /**\n * Get connection pool statistics.\n * Returns null if not connected.\n *\n * @remarks\n * MySQL2 pool exposes different stats than pg:\n * - _allConnections: all connections\n * - _freeConnections: idle connections\n * - _connectionQueue: waiting requests\n */\n getPoolStats(): PoolStats | null {\n if (!this.pool) {\n return null;\n }\n\n // mysql2 Pool internal properties (cast to access internals)\n const poolInternal = this.pool as unknown as {\n pool?: {\n _allConnections?: { length: number };\n _freeConnections?: { length: number };\n _connectionQueue?: { length: number };\n };\n };\n\n const internal = poolInternal.pool;\n if (!internal) {\n return {\n total: 0,\n idle: 0,\n waiting: 0,\n active: 0,\n };\n }\n\n const total = internal._allConnections?.length ?? 0;\n const idle = internal._freeConnections?.length ?? 0;\n const waiting = internal._connectionQueue?.length ?? 0;\n\n return {\n total,\n idle,\n waiting,\n active: total - idle,\n };\n }\n\n /**\n * Execute a raw SQL query.\n *\n * @param sql - SQL query string with ? placeholders\n * @param params - Query parameters\n * @returns Query results\n *\n * @throws {DatabaseError} If query execution fails\n */\n async executeQuery<T = unknown>(\n sql: string,\n params: SqlParam[] = []\n ): Promise<T[]> {\n const pool = this.ensurePool();\n const startTime = Date.now();\n\n try {\n const [rows] = await pool.query<RowDataPacket[]>(\n sql,\n params as unknown[]\n );\n\n // Log query if logger configured\n if (this.config.logger?.query) {\n const durationMs = Date.now() - startTime;\n this.config.logger.query(sql, params, durationMs);\n }\n\n return rows as T[];\n } catch (error) {\n throw this.classifyError(error, sql);\n }\n }\n\n /**\n * Execute work within a transaction.\n *\n * @param work - Function containing transactional operations\n * @param options - Transaction options (isolation level, timeout, retry)\n * @returns Result of the work function\n *\n * @remarks\n * MySQL transactions support isolation levels. Automatic retry is\n * implemented for deadlocks (error 1213) when `retryCount` is specified.\n *\n * Note: Savepoints are disabled in this adapter for safety due to\n * MySQL's quirks with nested transactions.\n */\n async transaction<T>(\n work: (tx: TransactionContext) => Promise<T>,\n options?: TransactionOptions\n ): Promise<T> {\n // The calling flow's open transaction from BEGIN until COMMIT or ROLLBACK\n // has run, for `transactionOpenInFlow`.\n return this.runInFlowTransaction(() =>\n this.runTransactionAttempts(work, options)\n );\n }\n\n /** The attempts `transaction` makes, each on a connection of its own. */\n private async runTransactionAttempts<T>(\n work: (tx: TransactionContext) => Promise<T>,\n options?: TransactionOptions\n ): Promise<T> {\n const pool = this.ensurePool();\n const maxAttempts = (options?.retryCount ?? 0) + 1;\n const retryDelayMs = options?.retryDelayMs ?? 100;\n\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const connection = await pool.getConnection();\n const startTime = Date.now();\n // Set when the ROLLBACK failed (`returnTransactionConnection`).\n let rollbackFailed = false;\n // What `beginTransaction` changed on the session, to put back once the\n // transaction has ended.\n let restore: SessionRestore = null;\n\n try {\n // Begin transaction with options\n restore = await this.beginTransaction(connection, options);\n\n // Create transaction context\n const ctx = this.createTransactionContext(connection);\n\n // Execute callback\n const result = await work(ctx);\n\n // Commit transaction\n await connection.query(\"COMMIT\");\n\n // Log success\n if (this.config.logger?.debug) {\n const durationMs = Date.now() - startTime;\n this.config.logger.debug(\"Transaction committed\", {\n attempt,\n durationMs,\n });\n }\n\n return result;\n } catch (error) {\n // Rollback transaction\n await connection.query(\"ROLLBACK\").catch(() => {\n rollbackFailed = true;\n });\n\n lastError = error;\n\n // Work inside a transaction may throw to roll the write back — a\n // refused value, a denied permission — and that is the application's\n // verdict, not the driver's failure. Rethrown before the retry check as\n // well as before classification: a refusal re-run is the same refusal,\n // and the caller must receive the code and payload it raised rather\n // than a generic database error with the detail stripped out.\n if (isApplicationError(error)) throw error;\n\n // Check if error is retryable (deadlock only per approved approach)\n const mysqlError = error as { errno?: number; code?: string };\n const isRetryable = mysqlError.errno === 1213; // ER_LOCK_DEADLOCK\n\n if (isRetryable && attempt < maxAttempts) {\n if (this.config.logger?.warn) {\n this.config.logger.warn(\n `Transaction failed with deadlock, retrying (${attempt}/${maxAttempts})`,\n { errno: mysqlError.errno, attempt }\n );\n }\n await delay(retryDelayMs * attempt); // Exponential backoff\n continue;\n }\n\n throw this.classifyError(error);\n } finally {\n await returnTransactionConnection(connection, rollbackFailed, restore);\n }\n }\n\n // Should not reach here, but handle just in case\n throw this.classifyError(lastError);\n }\n\n /**\n * Get MySQL database capabilities.\n *\n * @remarks\n * MySQL has some limitations:\n * - No JSONB (uses JSON)\n * - No arrays\n * - No native ILIKE\n * - No RETURNING clause\n * - Savepoints disabled for safety\n */\n getCapabilities(): DatabaseCapabilities {\n return {\n dialect: \"mysql\",\n supportsJsonb: false, // MySQL uses JSON, not JSONB\n supportsJson: true,\n supportsArrays: false, // MySQL doesn't support array types\n supportsGeneratedColumns: true, // MySQL 5.7.6+\n supportsFts: true, // MySQL has FULLTEXT indexes\n supportsIlike: false, // No native ILIKE, use LOWER() LIKE\n supportsReturning: false, // No RETURNING clause in MySQL\n supportsSavepoints: false, // Disabled for safety per approved approach\n supportsOnConflict: true, // ON DUPLICATE KEY UPDATE\n maxParamsPerQuery: 65535, // MySQL limit\n maxIdentifierLength: 64, // MySQL limit\n sharedRowLock: this.sharedRowLock, // Known once connected\n };\n }\n\n /**\n * Build a placeholder for MySQL (uses ? instead of $1, $2, etc.)\n *\n * @param _index - Parameter index (ignored for MySQL)\n * @returns The ? placeholder\n */\n protected buildPlaceholder(_index: number): string {\n return \"?\";\n }\n\n /**\n * Build multiple placeholders for MySQL.\n *\n * @param count - Number of placeholders needed\n * @param _startIndex - Starting index (ignored for MySQL)\n * @returns Comma-separated ? placeholders\n */\n protected buildPlaceholders(count: number, _startIndex: number = 0): string {\n return Array(count).fill(\"?\").join(\", \");\n }\n\n /**\n * Escape an identifier for MySQL (uses backticks instead of double quotes).\n *\n * @param identifier - The identifier to escape\n * @returns Escaped identifier with backticks\n */\n protected escapeIdentifier(identifier: string): string {\n // MySQL uses backticks for identifiers\n return `\\`${identifier.replace(/`/g, \"``\")}\\``;\n }\n\n // ============================================================\n // Protected Helper Methods\n // ============================================================\n\n /**\n * Ensures pool is connected and returns it.\n *\n * @throws {DatabaseError} If not connected\n */\n private ensurePool(): Pool {\n if (!this.pool) {\n throw createDatabaseError({\n kind: \"connection\",\n message: \"MySqlAdapter is not connected. Call connect() first.\",\n });\n }\n return this.pool;\n }\n\n /**\n * Return the typed Drizzle instance for MySQL.\n * Guarded for server-only usage and requires an active connection.\n *\n * @param schema - Optional schema for relational queries (db.query.*)\n * @returns Drizzle ORM instance wrapping the mysql2 pool connection\n * @throws {Error} If called in browser or not connected\n */\n getDrizzle<T = MySql2Database<AnyRelations>>(relations?: AnyRelations): T {\n if (typeof window !== \"undefined\") {\n throw new Error(\"getDrizzle() is server-only\");\n }\n const pool = this.ensurePool();\n if (!relations) {\n this.drizzleBare ??= this.poolDrizzle(pool);\n return this.drizzleBare as T;\n }\n let cached = this.drizzleByRelations.get(relations);\n if (!cached) {\n cached = this.poolDrizzle(pool, relations);\n this.drizzleByRelations.set(relations, cached);\n }\n return cached as T;\n }\n\n /**\n * A Drizzle handle on the pool, for `getDrizzle`.\n *\n * Its `transaction` runs on a connection this adapter checks out and\n * returns itself (`pinDrizzleTransactions`): destroyed rather than pooled\n * when no ROLLBACK could be confirmed on it. And it counts for\n * `transactionOpenInFlow`, as the adapter's does.\n */\n private poolDrizzle(pool: Pool, relations?: AnyRelations) {\n // drizzle v1's mysql2 driver takes the CALLBACK pool and connection,\n // which the mysql2/promise wrappers expose on `.pool` and `.connection`:\n // handed a wrapper, it throws (\"Cannot set properties of undefined\n // (setting 'supportBigNumbers')\"). The pre-v1 `mode` option is gone.\n const onClient = (client: CallbackPool | CallbackConnection) =>\n relations ? drizzle({ client, relations }) : drizzle({ client });\n const callbackPool = (pool as unknown as { pool: CallbackPool }).pool;\n return this.trackFlowTransactions(\n this.pinDrizzleTransactions(onClient(callbackPool), async () => {\n const connection = await pool.getConnection();\n return {\n drizzle: onClient(\n (connection as unknown as { connection: CallbackConnection })\n .connection\n ),\n rollback: () => connection.query(\"ROLLBACK\"),\n release: dirty => {\n if (dirty) connection.destroy();\n else connection.release();\n },\n };\n })\n );\n }\n\n /**\n * Builds mysql2 Pool configuration from adapter config.\n */\n private buildPoolConfig(): PoolOptions {\n const config: PoolOptions = {};\n\n // Connection string or explicit options\n if (this.config.url) {\n config.uri = this.config.url;\n } else {\n if (this.config.host) config.host = this.config.host;\n if (this.config.port) config.port = this.config.port;\n if (this.config.database) config.database = this.config.database;\n if (this.config.user) config.user = this.config.user;\n if (this.config.password) config.password = this.config.password;\n }\n\n // Pool settings - mysql2 uses different property names\n config.connectionLimit = this.config.pool?.max ?? DEFAULT_POOL_CONFIG.max;\n config.idleTimeout =\n this.config.pool?.idleTimeoutMs ?? DEFAULT_POOL_CONFIG.idleTimeoutMs;\n config.connectTimeout =\n this.config.pool?.connectionTimeoutMs ??\n DEFAULT_POOL_CONFIG.connectionTimeoutMs;\n\n // Enable waiting for connections when pool is full\n config.waitForConnections = true;\n config.queueLimit = 0; // Unlimited queue\n\n // SSL configuration\n if (this.config.ssl) {\n if (typeof this.config.ssl === \"boolean\") {\n config.ssl = this.config.ssl ? {} : undefined;\n } else {\n config.ssl = {\n rejectUnauthorized: this.config.ssl.rejectUnauthorized,\n ca: this.config.ssl.ca,\n cert: this.config.ssl.cert,\n key: this.config.ssl.key,\n };\n }\n }\n\n // MySQL-specific options\n if (this.config.timezone) {\n config.timezone = this.config.timezone;\n }\n\n if (this.config.charset) {\n config.charset = this.config.charset;\n }\n\n // Enable multiple statements if needed (disabled by default for security)\n config.multipleStatements = false;\n\n // Date handling\n config.dateStrings = false; // Return Date objects\n\n return config;\n }\n\n /**\n * Begins a transaction with the specified options, and returns what it\n * changed on the session for `restoreSession` to put back.\n */\n private async beginTransaction(\n connection: PoolConnection,\n options?: TransactionOptions\n ): Promise<SessionRestore> {\n // Set isolation level if specified (must be done before BEGIN)\n if (options?.isolationLevel) {\n const isolationMap: Record<string, string> = {\n \"read uncommitted\": \"READ UNCOMMITTED\",\n \"read committed\": \"READ COMMITTED\",\n \"repeatable read\": \"REPEATABLE READ\",\n serializable: \"SERIALIZABLE\",\n };\n const level = isolationMap[options.isolationLevel];\n if (level) {\n await connection.query(`SET TRANSACTION ISOLATION LEVEL ${level}`);\n }\n }\n\n // Set read-only mode if specified\n if (options?.readOnly) {\n await connection.query(\"SET TRANSACTION READ ONLY\");\n }\n\n // Begin the transaction\n await connection.query(\"START TRANSACTION\");\n\n // Set lock wait timeout if specified\n if (options?.timeoutMs) {\n // Read first, so the session's own value can be put back once the\n // transaction has ended (`SessionRestore`).\n const [rows] = await connection.query<RowDataPacket[]>(\n \"SELECT @@SESSION.innodb_lock_wait_timeout AS timeout\"\n );\n const previous = Number(rows[0]?.timeout);\n // MySQL uses seconds for lock_wait_timeout\n const timeoutSeconds = Math.ceil(options.timeoutMs / 1000);\n await connection.query(\n `SET SESSION innodb_lock_wait_timeout = ${timeoutSeconds}`\n );\n return { lockWaitTimeout: Number.isInteger(previous) ? previous : null };\n }\n return null;\n }\n\n /**\n * Creates a TransactionContext for the given connection.\n *\n * @remarks\n * Note: Savepoint methods are not implemented (set to undefined)\n * as savepoints are disabled in this adapter per approved approach.\n */\n /**\n * Upsert with the meaning `INSERT … ON CONFLICT (target)` has on PostgreSQL\n * and SQLite, on the tables where MySQL can keep that promise.\n *\n * MySQL cannot limit a duplicate to one key: `ON DUPLICATE KEY UPDATE`\n * fires on a collision with ANY unique key, and a failed insert does not\n * say reliably which one. So the conflict target must be the table's only\n * unique key apart from its primary key, and any other table is refused\n * before anything is written. On such a table the row is inserted first —\n * its validation and triggers apply, as they do before `ON CONFLICT`\n * elsewhere — and a duplicate is resolved by a locking read of the target\n * key, which sees the latest committed row rather than the transaction's\n * snapshot. The row found is kept as it is when there is nothing to update\n * (a no-op assignment would still run its update triggers), or updated by\n * its key. No row there means the collision was on the primary key, and it\n * is refused as `ON CONFLICT (target)` refuses it.\n *\n * The steps run in the caller's transaction, or in one of their own, since a\n * locking read locks nothing past its statement under autocommit. Rows are\n * read back by their primary key, so a trigger that rewrites the conflict\n * value still returns the row stored. The conflict columns must also be\n * given values: MySQL cannot look a row up by a key the database would only\n * fill in itself. A conflict is resolved on the caller's key value: a\n * BEFORE INSERT trigger that moves the key onto another row's value is\n * refused as a unique violation rather than resolved onto that row. A failed insert rolls back only itself on MySQL, so a\n * caller's transaction stays usable.\n */\n override async upsert<T = unknown>(\n table: string,\n data: Record<string, unknown>,\n options: UpsertOptions,\n executor?: unknown\n ): Promise<T> {\n const tableObj = this.getTableObject(table) as MySqlTable | undefined;\n // Unknown table: the base method reports it as every CRUD method does.\n if (!tableObj) return super.upsert<T>(table, data, options, executor);\n let target: { where: SQL | undefined; nullKey: boolean };\n try {\n // Judged before anything else, so a refused call takes no connection.\n target = this.upsertTarget(tableObj, table, data, options);\n } catch (error) {\n throw this.handleQueryError(error, \"upsert\", table);\n }\n // A locking read holds its lock only inside a transaction: under autocommit\n // it is released when its own statement ends, and the next statement may\n // run on another pooled connection. Without the caller's transaction, the\n // insert, the read and the update get one of their own, on one connection.\n if (executor === undefined) {\n return this.transaction(tx => tx.upsert<T>(table, data, options));\n }\n try {\n const db = executor as MySql2Database<AnyRelations>;\n // A conflict key holding NULL never conflicts: a unique index admits any\n // number of NULLs. It is a plain insert, read back by its primary key.\n if (target.nullKey) {\n return ((await this.insertRow(db, tableObj, data)) ?? data) as T;\n }\n return (await this.insertOrResolve(\n db,\n tableObj,\n data,\n options,\n target.where\n )) as T;\n } catch (error) {\n throw this.handleQueryError(error, \"upsert\", table);\n }\n }\n\n /**\n * What an upsert is keyed on: the target's condition, and whether its key\n * holds a NULL. Refuses a target this dialect cannot keep to, and a conflict\n * column left for the database to fill — MySQL cannot look a row up by a key\n * value only the database would supply.\n */\n private upsertTarget(\n tableObj: MySqlTable,\n table: string,\n data: Record<string, unknown>,\n options: UpsertOptions\n ): { where: SQL | undefined; nullKey: boolean } {\n // MySQL needs every conflict value whether or not it updates: the row is\n // found by them after a duplicate, so the keep-existing rule applies to\n // every call here.\n this.assertUpsertTarget(table, data, options, true);\n const key = this.conflictKey(tableObj, table, options.conflictColumns);\n const values = options.conflictColumns.map(column => data[column]);\n return {\n where: and(...key.map((column, i) => eq(column, values[i] as never))),\n nullKey: values.some(value => value === null),\n };\n }\n\n /**\n * The table's columns for a conflict target, refusing a target MySQL cannot\n * keep to: one that is not a primary or unique key, which an update could\n * spread over several rows, and one beside which the table has another\n * unique key, a collision on which MySQL would not tell apart.\n */\n private conflictKey(\n tableObj: MySqlTable,\n table: string,\n conflictColumns: readonly string[]\n ): Column[] {\n const record = tableObj as unknown as Record<string, Column | undefined>;\n const columns = conflictColumns.map(name => record[name]);\n const names = new Set(columns.map(column => column?.name));\n const isTarget = (key: readonly string[]) =>\n key.length === names.size && key.every(name => names.has(name));\n const { primary, unique } = keysOf(tableObj);\n // Every row this upsert returns is read back by its primary key, so a\n // table without one has no stable way to find the row it wrote.\n if (primary.length === 0) {\n throw createDatabaseError({\n kind: \"query\",\n message: `upsert on ${table}: MySQL upserts need a table with a primary key, to read back the row they write.`,\n });\n }\n const known = columns.every(column => column !== undefined);\n if (\n !known ||\n !(isTarget(primary) || unique.some(k => isTarget(k.columns)))\n ) {\n throw createDatabaseError({\n kind: \"query\",\n message: `upsert on ${table}: the conflict columns (${conflictColumns.join(\", \")}) are not a primary or unique key of the table.`,\n });\n }\n const others = unique.filter(key => !isTarget(key.columns));\n if (others.length > 0) {\n throw createDatabaseError({\n kind: \"query\",\n message: `upsert on ${table}: MySQL cannot limit a duplicate to the conflict columns (${conflictColumns.join(\", \")}) while the table has other unique keys (${others.map(key => key.name).join(\", \")}). Upsert only on a table whose one unique key besides the primary key is the conflict target, or insert and update inside a transaction.`,\n });\n }\n return columns;\n }\n\n /** The update an upsert applies to an existing row: never its key. */\n private updateValues(\n data: Record<string, unknown>,\n options: UpsertOptions\n ): Record<string, unknown> {\n const key = new Set(options.conflictColumns);\n const update: Record<string, unknown> = {};\n for (const column of options.updateColumns ?? Object.keys(data)) {\n if (!key.has(column) && column in data) update[column] = data[column];\n }\n return update;\n }\n\n /** The row matching `where`, by a locking (current) read. */\n private async lockedRow(\n db: MySql2Database<AnyRelations>,\n tableObj: MySqlTable,\n where: SQL | undefined\n ): Promise<unknown> {\n const rows = await db\n .select()\n .from(tableObj)\n .where(where)\n .limit(1)\n .for(\"update\");\n return rows[0];\n }\n\n /**\n * Insert the row, or resolve a duplicate on the target key. The insert is\n * read back by the primary key it reports, not by the conflict key: a\n * BEFORE INSERT trigger may have rewritten the conflict value, and the row\n * stored is the one to return.\n *\n * A duplicate is resolved when a row holds the TARGET key, whichever unique\n * key MySQL names in its error. PostgreSQL checks the target's index before\n * any other, so a row colliding on the target and on another key resolves\n * on the target there too; refusing it here because MySQL happened to check\n * the other index first would answer that case differently. A target row\n * committed by another transaction after this insert failed is the order in\n * which that transaction ran first, where PostgreSQL also resolves on it.\n */\n private async insertOrResolve(\n db: MySql2Database<AnyRelations>,\n tableObj: MySqlTable,\n data: Record<string, unknown>,\n options: UpsertOptions,\n where: SQL | undefined\n ): Promise<unknown> {\n let failure: unknown;\n try {\n const stored = await this.insertRow(db, tableObj, data);\n return stored ?? (await this.lockedRow(db, tableObj, where));\n } catch (error) {\n // Classified as everything else is, through the driver's own error\n // under Drizzle's wrapper (`classifyError`).\n if (this.classifyError(error).kind !== \"unique_violation\") throw error;\n failure = error;\n }\n const existing = await this.lockedRow(db, tableObj, where);\n // No row holds the target key: the collision was on another unique key,\n // refused as `ON CONFLICT (target)` refuses it, as the unique violation the\n // classifier reads it to be.\n if (existing === undefined) throw failure;\n const update = this.updateValues(data, options);\n if (Object.keys(update).length === 0) return existing;\n await db.update(tableObj).set(update).where(where);\n // Read back by the row's primary key as the update left it: the update may\n // set the key itself (every given column is updated by default, as `ON\n // CONFLICT DO UPDATE` does elsewhere), and a BEFORE UPDATE trigger may\n // have changed the conflict value the update was keyed on. A trigger that\n // changed the primary key instead leaves the conflict value standing, so\n // the row is looked for there next; one that changed both is not found.\n const identity = this.byIdentity(tableObj, {\n ...(existing as Record<string, unknown>),\n ...update,\n });\n const updated =\n identity === undefined\n ? undefined\n : await this.lockedRow(db, tableObj, identity);\n return updated ?? this.lockedRow(db, tableObj, where);\n }\n\n /**\n * Insert a row and read it back by its primary key: the value the caller\n * gave, or the one MySQL or the model generated, which `$returningId()`\n * reports and a given value it does not. Undefined when the table has no\n * primary key to read by.\n */\n private async insertRow(\n db: MySql2Database<AnyRelations>,\n tableObj: MySqlTable,\n data: Record<string, unknown>\n ): Promise<unknown> {\n const [generated] = (await db\n .insert(tableObj)\n .values(data as never)\n .$returningId()) as Record<string, unknown>[];\n // A key the caller gave wins; one given as undefined or null does not hide\n // the value MySQL generated for it.\n const given = Object.fromEntries(\n Object.entries(data).filter(\n ([, value]) => value !== undefined && value !== null\n )\n );\n const identity = this.byIdentity(tableObj, { ...generated, ...given });\n return identity === undefined\n ? undefined\n : this.lockedRow(db, tableObj, identity);\n }\n\n /**\n * A row's primary key as a condition, from a record keyed as the model's\n * properties are. Undefined when the table has no primary key or the record\n * lacks part of it.\n */\n private byIdentity(\n tableObj: MySqlTable,\n record: Record<string, unknown>\n ): SQL | undefined {\n const primary = new Set(keysOf(tableObj).primary);\n const parts = Object.entries(getColumns(tableObj)).filter(([, column]) =>\n primary.has(column.name)\n );\n if (\n parts.length === 0 ||\n parts.some(\n ([name]) => record[name] === undefined || record[name] === null\n )\n ) {\n return undefined;\n }\n return and(\n ...parts.map(([name, column]) => eq(column, record[name] as never))\n );\n }\n\n /** A table-level `primaryKey({ columns })`, read through the MySQL table config. */\n protected override compositePrimaryKey(\n tableObj: Record<string, unknown>\n ): object[] {\n return getTableConfig(\n tableObj as unknown as MySqlTable\n ).primaryKeys.flatMap(key => key.columns);\n }\n\n private createTransactionContext(\n connection: PoolConnection\n ): TransactionContext {\n // Bind a Drizzle instance to this transaction's checked-out connection so\n // the delegated CRUD methods run inside the transaction and see its\n // uncommitted rows. drizzle's mysql2 driver needs the underlying CALLBACK\n // connection, which the mysql2/promise wrapper exposes on `.connection`\n // (mirrors the `.pool` unwrap in getDrizzle()); getDrizzle() itself wraps\n // the pool, which would use a different connection. Built lazily and\n // memoized: transactions that use only raw execute/insert never construct\n // it.\n const txConnection = (\n connection as unknown as { connection: CallbackConnection }\n ).connection;\n const txHandles = this.transactionDrizzleHandles(relations =>\n relations\n ? drizzle({ client: txConnection, relations })\n : drizzle({ client: txConnection })\n );\n const txDb = txHandles.bare;\n return {\n drizzleWithRelations: txHandles.withRelations,\n\n execute: async <T = unknown>(\n sql: string,\n params: SqlParam[] = []\n ): Promise<T[]> => {\n const [rows] = await connection.query<RowDataPacket[]>(\n sql,\n params as unknown[]\n );\n return rows as T[];\n },\n\n // Run on the transaction-bound Drizzle instance rather than the pool, so\n // the statement is part of this transaction and sees its uncommitted rows.\n runStatement: async (statement: SQL): Promise<void> => {\n await txDb().execute(statement);\n },\n\n // mysql2 answers a `[rows, fields]` tuple; the transaction-bound instance\n // keeps the read inside this transaction so it sees its uncommitted writes.\n queryStatement: async <T = Record<string, unknown>>(\n statement: SQL\n ): Promise<T[]> => {\n const result = await txDb().execute(statement);\n // A tuple's first element is the rows. Anything else was not understood,\n // and must not reach a caller as \"there is nothing there\" — the same\n // reason the pooled `queryStatement` refuses rather than answering\n // empty.\n if (!Array.isArray(result)) {\n throw this.createDatabaseError(\n \"query\",\n \"Drizzle statement returned a result shape this adapter does not recognise; refusing to report it as an empty result.\",\n undefined\n );\n }\n return result[0] as unknown as T[];\n },\n\n lockRow: async (table: string, id: SqlParam): Promise<void> => {\n const idColumn = this.escapeIdentifier(\"id\");\n await connection.query(\n `SELECT ${idColumn} FROM ${this.escapeIdentifier(table)} ` +\n `WHERE ${idColumn} = ? FOR UPDATE`,\n [id] as unknown[]\n );\n },\n\n insert: async <T = unknown>(\n table: string,\n data: Record<string, unknown>,\n options?: InsertOptions\n ): Promise<T> => {\n const mapped = this.mapRowToRawSql(this.getTableObject(table), data);\n const columns = Object.keys(mapped);\n const values = Object.values(mapped);\n const placeholders = this.buildPlaceholders(values.length, 0);\n\n const sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map(c => this.escapeIdentifier(c)).join(\", \")}) VALUES (${placeholders})`;\n\n const [result] = await connection.query<ResultSetHeader>(sql, values);\n\n const ret = options?.returning;\n // No columns requested: skip the select-back reread entirely.\n if (Array.isArray(ret) && ret.length === 0) {\n return undefined as T;\n }\n\n // MySQL has no RETURNING; select the inserted row back. Project only the\n // requested columns so a large JSON snapshot is not read unless asked.\n const insertTableObj = this.getTableObject(table);\n // Each timestamp's wall clock, spelled out by the database. mysql2\n // turns one into a `Date` in the LOCAL zone before this code sees it,\n // and that conversion cannot be undone: a wall clock inside a\n // daylight-saving gap is normalized away.\n const aliases = this.dateWallClockAliases(insertTableObj, ret ?? \"*\");\n const spelled = aliases\n .map(\n a =>\n `DATE_FORMAT(${this.escapeIdentifier(a.sqlName)}, '%Y-%m-%dT%H:%i:%s.%f') AS ${this.escapeIdentifier(a.alias)}`\n )\n .join(\", \");\n const projected =\n !ret || ret === \"*\"\n ? \"*\"\n : this.mapColumnNamesToSql(insertTableObj, ret)\n .map(c => this.escapeIdentifier(c))\n .join(\", \");\n const selectList = spelled ? `${projected}, ${spelled}` : projected;\n\n // Prefer the primary key: auto-increment via insertId, otherwise a\n // supplied id (manually-keyed tables like nextly_versions). Matching by\n // all values is a last resort because `col = NULL` never matches, so a\n // row with nullable columns would not be found by that path.\n const idValue = result.insertId ? result.insertId : mapped.id;\n if (idValue !== undefined) {\n const [rows] = await connection.query<RowDataPacket[]>(\n `SELECT ${selectList} FROM ${this.escapeIdentifier(table)} WHERE id = ?`,\n [idValue]\n );\n return this.mapRowFromRawSql(insertTableObj, rows[0] as T, aliases);\n }\n\n const whereClauses = columns.map(\n c => `${this.escapeIdentifier(c)} = ?`\n );\n const [rows] = await connection.query<RowDataPacket[]>(\n `SELECT ${selectList} FROM ${this.escapeIdentifier(table)} WHERE ${whereClauses.join(\" AND \")} LIMIT 1`,\n values\n );\n return this.mapRowFromRawSql(insertTableObj, rows[0] as T, aliases);\n },\n\n insertMany: async <T = unknown>(\n table: string,\n data: Record<string, unknown>[],\n options?: InsertOptions\n ): Promise<T[]> => {\n if (data.length === 0) return [];\n const retMany = options?.returning;\n const skipReread = Array.isArray(retMany) && retMany.length === 0;\n\n const tableObj = this.getTableObject(table);\n const mappedRecords = data.map(r => this.mapRowToRawSql(tableObj, r));\n const columns = Object.keys(mappedRecords[0]);\n const allValues: unknown[] = [];\n const valuesClauses: string[] = [];\n\n for (const record of mappedRecords) {\n const placeholders: string[] = [];\n for (const col of columns) {\n allValues.push(record[col]);\n placeholders.push(\"?\");\n }\n valuesClauses.push(`(${placeholders.join(\", \")})`);\n }\n\n const sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map(c => this.escapeIdentifier(c)).join(\", \")}) VALUES ${valuesClauses.join(\", \")}`;\n\n const [result] = await connection.query<ResultSetHeader>(\n sql,\n allValues\n );\n\n // For bulk insert, we need to SELECT the inserted rows\n // MySQL's insertId gives the first auto-increment ID\n if (!skipReread && result.insertId && result.affectedRows > 0) {\n const ids: number[] = [];\n for (let i = 0; i < result.affectedRows; i++) {\n ids.push(result.insertId + i);\n }\n const placeholders = ids.map(() => \"?\").join(\", \");\n const bulkAliases = this.dateWallClockAliases(tableObj, \"*\");\n const bulkSpelled = bulkAliases\n .map(\n a =>\n `DATE_FORMAT(${this.escapeIdentifier(a.sqlName)}, '%Y-%m-%dT%H:%i:%s.%f') AS ${this.escapeIdentifier(a.alias)}`\n )\n .join(\", \");\n const [rows] = await connection.query<RowDataPacket[]>(\n `SELECT *${bulkSpelled ? `, ${bulkSpelled}` : \"\"} FROM ${this.escapeIdentifier(table)} WHERE id IN (${placeholders})`,\n ids\n );\n return (rows as T[]).map(r =>\n this.mapRowFromRawSql(tableObj, r, bulkAliases)\n );\n }\n\n // Fallback: return empty if we can't determine inserted rows\n return [];\n },\n\n // Adapter-built, as `insert` above is; `transactionUpdate` says why.\n // A column the model does not declare binds natively, as every value\n // on this path's insert does.\n update: this.transactionUpdate(\n txDb,\n async statement => {\n // No RETURNING on MySQL: nothing to report, the read-back is by\n // the caller's predicate.\n await txDb().execute(statement);\n return undefined;\n },\n // Structured values as JSON text: mysql2's formatter spells an object\n // as `key = value` pairs and an array as a value list, neither JSON.\n value => this.bindUnmodeledStructuredAsJson(value)\n ),\n\n ...this.createTransactionForwarders(txDb),\n\n // Savepoints disabled per approved approach\n savepoint: undefined,\n rollbackToSavepoint: undefined,\n releaseSavepoint: undefined,\n };\n }\n\n /**\n * Classifies a MySQL error into a DatabaseError.\n *\n * @param error - Original error from mysql2\n * @param sql - SQL statement that caused the error (optional)\n * @returns DatabaseError with proper classification\n */\n protected override classifyError(\n error: unknown,\n sql?: string\n ): DatabaseError {\n // Why short-circuit on existing DatabaseError: F17's\n // UnsupportedDialectVersionError is already a typed DatabaseError with\n // kind: \"unsupported_version\" plus detectedVersion/requiredVersion\n // fields. Re-wrapping it here would erase those fields and re-tag it\n // as kind: \"unknown\".\n if (isDatabaseError(error)) return error;\n\n // Classified from mysql2's own error, which Drizzle puts on `cause` when it\n // wraps a failed query (`driverErrorIn`); it is the one carrying `errno`.\n const mysqlError = this.driverErrorIn<{\n errno?: number;\n code?: string;\n sqlState?: string;\n message?: string;\n sql?: string;\n cause?: unknown;\n }>(error, candidate => typeof candidate.errno === \"number\");\n\n // Determine error kind from MySQL error number\n const kind: DatabaseErrorKind =\n (mysqlError.errno && MYSQL_ERROR_CODES[mysqlError.errno]) || \"unknown\";\n\n // Build error message\n let message = mysqlError.message ?? String(error);\n if (sql && kind === \"query\") {\n message = `Query failed: ${message}`;\n }\n\n return createDatabaseError({\n kind,\n message,\n code: mysqlError.code ?? mysqlError.errno?.toString(),\n detail: mysqlError.sql,\n cause: error instanceof Error ? error : undefined,\n });\n }\n}\n\n/** A table's keys by database column name, as its model declares them. */\ninterface TableKeys {\n primary: string[];\n unique: { name: string; columns: string[] }[];\n}\n\nconst TABLE_KEYS = new WeakMap<MySqlTable, TableKeys>();\n\n/**\n * A table's primary key and its unique keys other than the primary key, read\n * from its model once and kept for the table's lifetime: a model is not\n * changed in place, a new schema brings new table objects.\n */\nfunction keysOf(tableObj: MySqlTable): TableKeys {\n const cached = TABLE_KEYS.get(tableObj);\n if (cached) return cached;\n const config = getTableConfig(tableObj);\n const primary = [\n ...config.columns.filter(column => column.primary),\n ...config.primaryKeys.flatMap(key => key.columns),\n ].map(column => column.name);\n const unique = [\n ...config.columns\n .filter(column => column.isUnique && !column.primary)\n .map(column => ({\n // Drizzle's own name for an unnamed column-level unique key.\n name: column.uniqueName ?? `${config.name}_${column.name}_unique`,\n columns: [column.name],\n })),\n ...config.uniqueConstraints.map(constraint => ({\n name: constraint.name,\n columns: constraint.columns.map(column => column.name),\n })),\n ...config.indexes\n .filter(index => index.config.unique === true)\n .map(index => ({\n name: index.config.name,\n columns: (index.config.columns as { name: string }[]).map(\n column => column.name\n ),\n })),\n ];\n const keys = { primary, unique };\n TABLE_KEYS.set(tableObj, keys);\n return keys;\n}\n\n/**\n * Create a MySQL database adapter.\n *\n * @param config - MySQL adapter configuration\n * @returns A new MySqlAdapter instance\n *\n * @example\n * ```typescript\n * // Simple usage with URL\n * const adapter = createMySqlAdapter({\n * url: 'mysql://user:pass@localhost:3306/mydb',\n * });\n *\n * // Full configuration\n * const adapter = createMySqlAdapter({\n * url: process.env.DATABASE_URL!,\n * pool: {\n * min: 2,\n * max: 20,\n * idleTimeoutMs: 30000,\n * connectionTimeoutMs: 10000,\n * },\n * ssl: {\n * rejectUnauthorized: true,\n * },\n * });\n *\n * await adapter.connect();\n * ```\n */\nexport function createMySqlAdapter(config: MySqlAdapterConfig): MySqlAdapter {\n return new MySqlAdapter(config);\n}\n\n/**\n * Type guard to check if a value is a MySqlAdapter.\n *\n * @param value - Value to check\n * @returns True if value is a MySqlAdapter instance\n *\n * @example\n * ```typescript\n * if (isMySqlAdapter(adapter)) {\n * // TypeScript knows adapter is MySqlAdapter\n * console.log('Using MySQL');\n * }\n * ```\n */\nexport function isMySqlAdapter(value: unknown): value is MySqlAdapter {\n return value instanceof MySqlAdapter;\n}\n"]}
1
+ {"version":3,"file":"index.cjs","names":["poolWaitTimeoutError","DrizzleAdapter","mysql","checkDialectVersion","acceptsForShare","isApplicationError","createDatabaseError","drizzle","and","eq","getColumns","getTableConfig","isDatabaseError"],"sources":["../src/pool-wait.ts","../src/index.ts"],"sourcesContent":["/**\n * The bounded wait for a pooled connection.\n *\n * mysql2 has no such bound. A request that finds every connection in use is\n * queued until one is released, however long that takes, so a database that\n * stays busy holds every request behind it indefinitely. This bounds the wait\n * the way pg-pool's `connectionTimeoutMillis` does: past the bound, the\n * request fails with the adapters' own pool-wait timeout error, which core\n * answers with \"database busy\".\n *\n * Only the wait in the queue: a request that opens a new connection is bounded\n * by mysql2's `connectTimeout` instead, set from the same setting, and a\n * connection that cannot be opened is a database that cannot be reached\n * rather than one that is busy.\n */\nimport { poolWaitTimeoutError } from \"@nextlyhq/adapter-drizzle/types\";\n\n/** A connection the pool hands out, as far as the bound needs one. */\ninterface QueuedConnection {\n release(): void;\n}\n\ntype GetConnectionCallback = (\n err: Error | null,\n connection?: QueuedConnection\n) => void;\n\n/**\n * The part of mysql2's callback pool the bound uses. Declared here because\n * mysql2's mixin typings drop the EventEmitter methods its pool has.\n */\nexport interface QueueingPool {\n getConnection(callback: GetConnectionCallback): void;\n once(event: \"enqueue\", listener: () => void): unknown;\n removeListener(event: \"enqueue\", listener: () => void): unknown;\n /** mysql2's queue of waiting requests (a Denque). */\n _connectionQueue?: {\n length: number;\n peekAt(index: number): unknown;\n removeOne(index: number): unknown;\n };\n}\n\n/**\n * Takes a request that gave up out of the pool's queue, so a pool that stays\n * saturated does not collect every request that has already failed, and a\n * released connection goes to one still waiting. Returns whether it was\n * there: with diagnostics tracing on, mysql2 queues a wrapper of the\n * callback rather than the callback itself, and then it stays queued until a\n * connection reaches it.\n */\nfunction leaveQueue(pool: QueueingPool, waiting: GetConnectionCallback) {\n const queue = pool._connectionQueue;\n if (!queue) return false;\n for (let at = 0; at < queue.length; at++) {\n if (queue.peekAt(at) === waiting) {\n queue.removeOne(at);\n return true;\n }\n }\n return false;\n}\n\n/**\n * Makes `pool` fail a request that has waited `boundMs` in its queue for a\n * connection, and returns it. A bound of 0 leaves the wait unbounded, as\n * pg-pool reads a `connectionTimeoutMillis` of 0.\n *\n * Replaces the pool's own `getConnection`, which its `query` and `execute`\n * go through, so every path to a connection is bounded: the adapter's\n * statements, its transactions, and the Drizzle handle core services query\n * through.\n *\n * A request that gives up leaves the queue. Where mysql2 cannot be asked to\n * drop it, the connection it is eventually handed is released straight back\n * rather than held by a request that has already failed.\n */\nexport function boundPoolWait<P extends QueueingPool>(\n pool: P,\n boundMs: number\n): P {\n if (boundMs <= 0) return pool;\n const getConnection = pool.getConnection.bind(pool);\n const bounded = (callback: GetConnectionCallback) => {\n let answered = false;\n // Set only once the request has queued; read by the answer that ends it.\n const wait: { timer?: ReturnType<typeof setTimeout> } = {};\n // mysql2 emits `enqueue` synchronously, inside this call, exactly when\n // the request joins the queue rather than taking or opening a connection.\n let queued = false;\n const onEnqueue = () => (queued = true);\n pool.once(\"enqueue\", onEnqueue);\n const waiting: GetConnectionCallback = (err, connection) => {\n if (answered) {\n connection?.release();\n return;\n }\n answered = true;\n clearTimeout(wait.timer);\n callback(err, connection);\n };\n getConnection(waiting);\n pool.removeListener(\"enqueue\", onEnqueue);\n if (!queued || answered) return;\n wait.timer = setTimeout(() => {\n answered = true;\n leaveQueue(pool, waiting);\n callback(poolWaitTimeoutError(boundMs));\n }, boundMs);\n };\n pool.getConnection = bounded;\n return pool;\n}\n","/**\n * @nextlyhq/adapter-mysql\n *\n * MySQL database adapter for Nextly.\n * Extends DrizzleAdapter from @nextlyhq/adapter-drizzle to provide MySQL-specific functionality.\n *\n * @remarks\n * This adapter uses the mysql2 package for database connectivity and provides:\n * - Connection pooling via mysql2 Pool\n * - Full transaction support with isolation levels\n * - CRUD operations with workarounds for missing RETURNING clause\n * - MySQL-specific error classification\n * - Automatic retry for deadlocks (error 1213)\n *\n * @example\n * ```typescript\n * import { createMySqlAdapter } from '@nextlyhq/adapter-mysql';\n *\n * const adapter = createMySqlAdapter({\n * url: process.env.DATABASE_URL!,\n * });\n *\n * await adapter.connect();\n *\n * // Query data\n * const users = await adapter.select('users', {\n * where: { and: [{ column: 'status', op: '=', value: 'active' }] },\n * limit: 10,\n * });\n *\n * await adapter.disconnect();\n * ```\n *\n * @packageDocumentation\n */\n\nimport { DrizzleAdapter } from \"@nextlyhq/adapter-drizzle\";\n// F17: connect-time DB version check shared across all adapters.\nimport {\n createDatabaseError,\n isDatabaseError,\n type MySqlAdapterConfig,\n type DatabaseCapabilities,\n type PoolStats,\n type TransactionContext,\n type TransactionOptions,\n type SqlParam,\n type WhereClause,\n type WhereCondition,\n type WhereOperator,\n type SelectOptions,\n type InsertOptions,\n type UpdateOptions,\n type DeleteOptions,\n type UpsertOptions,\n type OrderBySpec,\n type JoinSpec,\n type DatabaseError,\n type DatabaseErrorKind,\n type BaseAdapterConfig,\n type AdapterLogger,\n type PoolConfig,\n type SslConfig,\n isApplicationError,\n} from \"@nextlyhq/adapter-drizzle/types\";\nimport {\n acceptsForShare,\n checkDialectVersion,\n} from \"@nextlyhq/adapter-drizzle/version-check\";\nimport { and, eq, getColumns } from \"drizzle-orm\";\nimport type { AnyRelations, Column, SQL } from \"drizzle-orm\";\nimport { getTableConfig, type MySqlTable } from \"drizzle-orm/mysql-core\";\nimport { drizzle, type MySql2Database } from \"drizzle-orm/mysql2\";\nimport type {\n Pool as CallbackPool,\n Connection as CallbackConnection,\n} from \"mysql2\";\nimport mysql from \"mysql2/promise\";\nimport type {\n PoolOptions,\n RowDataPacket,\n ResultSetHeader,\n} from \"mysql2/promise\";\n\nimport { boundPoolWait, type QueueingPool } from \"./pool-wait\";\n\n// mysql2 type definitions use mixin patterns that TypeScript struggles with.\n// We define explicit interfaces for the methods we need.\n\n/**\n * Query result type - either rows or a result header\n */\ntype QueryResult = RowDataPacket[] | RowDataPacket[][] | ResultSetHeader;\n\n/**\n * Queryable interface for mysql2 connections\n */\ninterface Queryable {\n query<T extends QueryResult>(sql: string): Promise<[T, unknown]>;\n query<T extends QueryResult>(\n sql: string,\n values: unknown[]\n ): Promise<[T, unknown]>;\n}\n\n/**\n * mysql2 Pool interface with query method\n */\ninterface Pool extends Queryable {\n getConnection(): Promise<PoolConnection>;\n end(): Promise<void>;\n pool?: {\n _allConnections?: { length: number };\n _freeConnections?: { length: number };\n _connectionQueue?: { length: number };\n };\n}\n\n/**\n * mysql2 PoolConnection interface with query and release methods\n */\ninterface PoolConnection extends Queryable {\n /** Returns the connection to the pool, for the next request to use. */\n release(): void;\n /** Closes the connection and removes it from the pool. */\n destroy(): void;\n}\n\n/**\n * What a transaction changed on its connection's session, to put back before\n * the connection returns to the pool; null when it changed nothing.\n *\n * MySQL has no transaction-scoped form of `innodb_lock_wait_timeout` or\n * `sql_mode`: a `SET SESSION` outlives the transaction, and the pooled\n * connection would carry one transaction's setting into every later query\n * handed it. Each field present is the session's value from before the\n * change, or null when it could not be read, and then the connection cannot\n * be put back.\n */\ntype SessionRestore = {\n lockWaitTimeout?: number | null;\n sqlMode?: string | null;\n} | null;\n\n/**\n * Puts back what a transaction changed on its connection's session. False\n * when that could not be done, and the connection must not be pooled.\n */\nasync function restoreSession(\n connection: PoolConnection,\n restore: SessionRestore\n): Promise<boolean> {\n if (restore === null) return true;\n if (restore.lockWaitTimeout === null || restore.sqlMode === null) {\n return false;\n }\n try {\n if (restore.lockWaitTimeout !== undefined) {\n // An integer read from the server, never caller input.\n await connection.query(\n `SET SESSION innodb_lock_wait_timeout = ${restore.lockWaitTimeout}`\n );\n }\n if (restore.sqlMode !== undefined) {\n // Read from the server, and bound as a value all the same.\n await connection.query(\"SET SESSION sql_mode = ?\", [restore.sqlMode]);\n }\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Ends a transaction's hold on its connection: back to the pool once its\n * session is as the transaction found it, or closed when it is not. A\n * connection whose ROLLBACK failed (`rollbackFailed`) may still be inside\n * the transaction, and the next request handed it would write into a\n * transaction nobody commits.\n */\nasync function returnTransactionConnection(\n connection: PoolConnection,\n rollbackFailed: boolean,\n restore: SessionRestore\n): Promise<void> {\n if (!rollbackFailed && (await restoreSession(connection, restore))) {\n connection.release();\n } else {\n connection.destroy();\n }\n}\n\n// Re-export types for convenience\nexport type {\n MySqlAdapterConfig,\n DatabaseCapabilities,\n PoolStats,\n TransactionContext,\n TransactionOptions,\n SqlParam,\n WhereClause,\n WhereCondition,\n WhereOperator,\n SelectOptions,\n InsertOptions,\n UpdateOptions,\n DeleteOptions,\n UpsertOptions,\n OrderBySpec,\n JoinSpec,\n DatabaseError,\n DatabaseErrorKind,\n BaseAdapterConfig,\n AdapterLogger,\n PoolConfig,\n SslConfig,\n};\n\n/**\n * Package version\n */\nexport const VERSION = \"0.1.0\";\n\n/**\n * Default pool configuration values.\n */\nconst DEFAULT_POOL_CONFIG = {\n min: 2,\n max: 10,\n idleTimeoutMs: 30000,\n // How long a request waits for a connection, in the queue or opening one:\n // the same bound, and the same default, as the PostgreSQL adapter's.\n connectionTimeoutMs: 15000,\n};\n\n/**\n * MySQL error codes mapping to DatabaseErrorKind.\n *\n * @see https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html\n */\nconst MYSQL_ERROR_CODES: Record<number, DatabaseErrorKind> = {\n // Unique/Duplicate key violations\n 1022: \"unique_violation\", // ER_DUP_KEY\n 1062: \"unique_violation\", // ER_DUP_ENTRY\n 1169: \"unique_violation\", // ER_DUP_UNIQUE\n 1586: \"unique_violation\", // ER_DUP_ENTRY_WITH_KEY_NAME\n\n // Foreign key violations\n 1216: \"foreign_key_violation\", // ER_NO_REFERENCED_ROW\n 1217: \"foreign_key_violation\", // ER_ROW_IS_REFERENCED\n 1451: \"foreign_key_violation\", // ER_ROW_IS_REFERENCED_2\n 1452: \"foreign_key_violation\", // ER_NO_REFERENCED_ROW_2\n\n // Not null violations\n 1048: \"not_null_violation\", // ER_BAD_NULL_ERROR\n 1364: \"not_null_violation\", // ER_NO_DEFAULT_FOR_FIELD\n\n // Check constraint violations (MySQL 8.0.16+)\n 3819: \"check_violation\", // ER_CHECK_CONSTRAINT_VIOLATED\n\n // Deadlock\n 1213: \"deadlock\", // ER_LOCK_DEADLOCK\n\n // Timeout\n 1205: \"timeout\", // ER_LOCK_WAIT_TIMEOUT\n\n // Connection errors\n 1040: \"connection\", // ER_CON_COUNT_ERROR - Too many connections\n 1042: \"connection\", // ER_BAD_HOST_ERROR\n 1043: \"connection\", // ER_HANDSHAKE_ERROR\n 1044: \"connection\", // ER_DBACCESS_DENIED_ERROR\n 1045: \"connection\", // ER_ACCESS_DENIED_ERROR\n 1129: \"connection\", // ER_HOST_IS_BLOCKED\n 1130: \"connection\", // ER_HOST_NOT_PRIVILEGED\n 2002: \"connection\", // CR_CONNECTION_ERROR\n 2003: \"connection\", // CR_CONN_HOST_ERROR\n 2006: \"connection\", // CR_SERVER_GONE_ERROR\n 2013: \"connection\", // CR_SERVER_LOST\n\n // Query errors\n 1064: \"query\", // ER_PARSE_ERROR\n 1146: \"query\", // ER_NO_SUCH_TABLE\n 1054: \"query\", // ER_BAD_FIELD_ERROR\n};\n\n/**\n * Delay helper for retry logic.\n */\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * MySQL database adapter for Nextly.\n *\n * Extends the base DrizzleAdapter to provide MySQL-specific functionality\n * using the mysql2 package.\n *\n * @remarks\n * MySQL has some limitations compared to PostgreSQL:\n * - No native RETURNING clause (requires INSERT then SELECT)\n * - No native ILIKE (uses LOWER() LIKE workaround)\n * - No native JSONB (uses JSON type)\n * - No array types\n * - Savepoints disabled for safety (MySQL has nested transaction quirks)\n *\n * @example\n * ```typescript\n * const adapter = new MySqlAdapter({\n * url: 'mysql://user:pass@localhost:3306/mydb',\n * pool: { max: 20 },\n * });\n *\n * await adapter.connect();\n * ```\n */\nexport class MySqlAdapter extends DrizzleAdapter {\n // getDrizzle memoization: drizzle v1's constructor builds a relational\n // query builder per table in the relations config (~40 tables), and the\n // service layer resolves an instance on every db access — construct once\n // per relations object (identity-stable: the schema registry caches it\n // and hands out a NEW object on invalidation, which naturally misses\n // this cache and produces a fresh instance).\n private drizzleByRelations = new WeakMap<AnyRelations, unknown>();\n private drizzleBare: unknown;\n\n /**\n * The database dialect - always 'mysql' for this adapter.\n */\n readonly dialect = \"mysql\" as const;\n\n /**\n * Adapter configuration.\n */\n protected readonly config: MySqlAdapterConfig;\n\n /**\n * Connection pool instance.\n */\n private pool: Pool | null = null;\n\n /**\n * Connection state flag.\n */\n private connected = false;\n\n /**\n * Whether the server accepts `SELECT ... FOR SHARE`, read from its version\n * string at connect. Undefined until then, which callers treat as not known.\n */\n private sharedRowLock: boolean | undefined;\n\n /**\n * Creates a new MySQL adapter instance.\n *\n * @param config - Adapter configuration\n */\n constructor(config: MySqlAdapterConfig) {\n super();\n this.config = config;\n }\n\n /**\n * Connect to the MySQL database.\n * Creates a connection pool using mysql2.\n *\n * @remarks\n * This method initializes the connection pool and verifies connectivity\n * by executing a simple query. It is idempotent - calling it multiple\n * times will not create multiple pools.\n *\n * @throws {DatabaseError} If connection fails\n */\n async connect(): Promise<void> {\n if (this.connected && this.pool) {\n return;\n }\n\n try {\n const poolConfig = this.buildPoolConfig();\n const pool = mysql.createPool(poolConfig);\n // mysql2 queues a request for a connection without limit; it fails as\n // busy past the same bound a new connection gets to open.\n boundPoolWait(\n pool.pool as unknown as QueueingPool,\n poolConfig.connectTimeout ?? 0\n );\n // Cast to our Pool interface - mysql2's mixin types don't resolve properly\n this.pool = pool as unknown as Pool;\n\n // Verify connection with smoke test, then check dialect version.\n // Why: F17 hard-fails at connect on real MySQL <8.0 (no variant\n // token detected). Recognized variants (MariaDB, TiDB, Aurora,\n // PlanetScale, Vitess) log a warning via the adapter logger and\n // proceed. Truly unparseable strings hard-fail so users see the\n // issue at boot rather than mid-apply.\n const connection = await this.pool.getConnection();\n try {\n await connection.query(\"SELECT 1\");\n const { variant } = await checkDialectVersion(connection, \"mysql\", {\n // Why: route variant warnings through the adapter's logger so\n // users see a single, consistent log surface.\n onWarning: msg => this.config.logger?.warn?.(msg),\n });\n // MariaDB and TiDB connect through this adapter too, and reject\n // `FOR SHARE`; the capability tells callers which lock they can take.\n this.sharedRowLock = acceptsForShare(variant);\n this.connected = true;\n\n if (this.config.logger?.info) {\n this.config.logger.info(\"MySQL connection established\", {\n host: this.config.host ?? \"from URL\",\n database: this.config.database ?? \"from URL\",\n });\n }\n } finally {\n connection.release();\n }\n } catch (error) {\n // Clean up on failure\n if (this.pool) {\n await this.pool.end().catch(() => {});\n this.pool = null;\n }\n throw this.classifyError(error);\n }\n }\n\n /**\n * Disconnect from the MySQL database.\n * Gracefully closes the connection pool.\n *\n * @remarks\n * This method is idempotent - calling it multiple times is safe.\n * It waits for all connections to be released before shutting down.\n */\n async disconnect(): Promise<void> {\n // Detach the pool FIRST, then drop the memoized drizzle instances —\n // this closes the repopulation window where a concurrent getDrizzle()\n // call during the (async) pool.end() could cache an instance wrapping\n // the closing pool.\n const pool = this.pool;\n this.pool = null;\n this.drizzleBare = undefined;\n this.drizzleByRelations = new WeakMap();\n if (!pool) {\n return;\n }\n\n try {\n await pool.end();\n\n if (this.config.logger?.info) {\n this.config.logger.info(\"MySQL connection closed\");\n }\n } finally {\n this.connected = false;\n }\n }\n\n /**\n * Check if connected to the database.\n */\n isConnected(): boolean {\n return this.connected && this.pool !== null;\n }\n\n /**\n * Get connection pool statistics.\n * Returns null if not connected.\n *\n * @remarks\n * MySQL2 pool exposes different stats than pg:\n * - _allConnections: all connections\n * - _freeConnections: idle connections\n * - _connectionQueue: waiting requests\n */\n getPoolStats(): PoolStats | null {\n if (!this.pool) {\n return null;\n }\n\n // mysql2 Pool internal properties (cast to access internals)\n const poolInternal = this.pool as unknown as {\n pool?: {\n _allConnections?: { length: number };\n _freeConnections?: { length: number };\n _connectionQueue?: { length: number };\n };\n };\n\n const internal = poolInternal.pool;\n if (!internal) {\n return {\n total: 0,\n idle: 0,\n waiting: 0,\n active: 0,\n };\n }\n\n const total = internal._allConnections?.length ?? 0;\n const idle = internal._freeConnections?.length ?? 0;\n const waiting = internal._connectionQueue?.length ?? 0;\n\n return {\n total,\n idle,\n waiting,\n active: total - idle,\n };\n }\n\n /**\n * Execute a raw SQL query.\n *\n * @param sql - SQL query string with ? placeholders\n * @param params - Query parameters\n * @returns Query results\n *\n * @throws {DatabaseError} If query execution fails\n */\n async executeQuery<T = unknown>(\n sql: string,\n params: SqlParam[] = []\n ): Promise<T[]> {\n const pool = this.ensurePool();\n const startTime = Date.now();\n\n try {\n // Outside the calling flow's transaction, if it has one (`notePoolAccess`).\n this.notePoolAccess(sql);\n const [rows] = await pool.query<RowDataPacket[]>(\n sql,\n params as unknown[]\n );\n\n // Log query if logger configured\n if (this.config.logger?.query) {\n const durationMs = Date.now() - startTime;\n this.config.logger.query(sql, params, durationMs);\n }\n\n return rows as T[];\n } catch (error) {\n throw this.classifyError(error, sql);\n }\n }\n\n /**\n * Execute work within a transaction.\n *\n * @param work - Function containing transactional operations\n * @param options - Transaction options (isolation level, timeout, retry)\n * @returns Result of the work function\n *\n * @remarks\n * MySQL transactions support isolation levels. Automatic retry is\n * implemented for deadlocks (error 1213) when `retryCount` is specified.\n *\n * Note: Savepoints are disabled in this adapter for safety due to\n * MySQL's quirks with nested transactions.\n */\n async transaction<T>(\n work: (tx: TransactionContext) => Promise<T>,\n options?: TransactionOptions\n ): Promise<T> {\n // The calling flow's open transaction from BEGIN until COMMIT or ROLLBACK\n // has run, for `transactionOpenInFlow`.\n return this.runInFlowTransaction(() =>\n this.runTransactionAttempts(work, options)\n );\n }\n\n /** The attempts `transaction` makes, each on a connection of its own. */\n private async runTransactionAttempts<T>(\n work: (tx: TransactionContext) => Promise<T>,\n options?: TransactionOptions\n ): Promise<T> {\n const pool = this.ensurePool();\n const maxAttempts = (options?.retryCount ?? 0) + 1;\n const retryDelayMs = options?.retryDelayMs ?? 100;\n\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const connection = await this.connectFlowTransaction(() =>\n pool.getConnection()\n );\n const startTime = Date.now();\n // Set when the ROLLBACK failed (`returnTransactionConnection`).\n let rollbackFailed = false;\n // What `beginTransaction` changed on the session, to put back once the\n // transaction has ended. Filled in as each change lands, so a setup\n // that fails part way still puts back what it had already changed.\n const restore: NonNullable<SessionRestore> = {};\n\n try {\n // Begin transaction with options\n await this.beginTransaction(connection, options, restore);\n\n // Create transaction context\n const ctx = this.createTransactionContext(connection);\n\n // Execute callback\n const result = await work(ctx);\n\n // Commit transaction\n await connection.query(\"COMMIT\");\n\n // Log success\n if (this.config.logger?.debug) {\n const durationMs = Date.now() - startTime;\n this.config.logger.debug(\"Transaction committed\", {\n attempt,\n durationMs,\n });\n }\n\n return result;\n } catch (error) {\n // Rollback transaction\n await connection.query(\"ROLLBACK\").catch(() => {\n rollbackFailed = true;\n });\n\n lastError = error;\n\n // Work inside a transaction may throw to roll the write back — a\n // refused value, a denied permission — and that is the application's\n // verdict, not the driver's failure. Rethrown before the retry check as\n // well as before classification: a refusal re-run is the same refusal,\n // and the caller must receive the code and payload it raised rather\n // than a generic database error with the detail stripped out.\n if (isApplicationError(error)) throw error;\n\n // Check if error is retryable (deadlock only per approved approach)\n const mysqlError = error as { errno?: number; code?: string };\n const isRetryable = mysqlError.errno === 1213; // ER_LOCK_DEADLOCK\n\n if (isRetryable && attempt < maxAttempts) {\n if (this.config.logger?.warn) {\n this.config.logger.warn(\n `Transaction failed with deadlock, retrying (${attempt}/${maxAttempts})`,\n { errno: mysqlError.errno, attempt }\n );\n }\n await delay(retryDelayMs * attempt); // Exponential backoff\n continue;\n }\n\n throw this.classifyError(error);\n } finally {\n await returnTransactionConnection(connection, rollbackFailed, restore);\n }\n }\n\n // Should not reach here, but handle just in case\n throw this.classifyError(lastError);\n }\n\n /**\n * Get MySQL database capabilities.\n *\n * @remarks\n * MySQL has some limitations:\n * - No JSONB (uses JSON)\n * - No arrays\n * - No native ILIKE\n * - No RETURNING clause\n * - Savepoints disabled for safety\n */\n getCapabilities(): DatabaseCapabilities {\n return {\n dialect: \"mysql\",\n supportsJsonb: false, // MySQL uses JSON, not JSONB\n supportsJson: true,\n supportsArrays: false, // MySQL doesn't support array types\n supportsGeneratedColumns: true, // MySQL 5.7.6+\n supportsFts: true, // MySQL has FULLTEXT indexes\n supportsIlike: false, // No native ILIKE, use LOWER() LIKE\n supportsReturning: false, // No RETURNING clause in MySQL\n supportsSavepoints: false, // Disabled for safety per approved approach\n supportsOnConflict: true, // ON DUPLICATE KEY UPDATE\n maxParamsPerQuery: 65535, // MySQL limit\n maxIdentifierLength: 64, // MySQL limit\n sharedRowLock: this.sharedRowLock, // Known once connected\n };\n }\n\n /**\n * Build a placeholder for MySQL (uses ? instead of $1, $2, etc.)\n *\n * @param _index - Parameter index (ignored for MySQL)\n * @returns The ? placeholder\n */\n protected buildPlaceholder(_index: number): string {\n return \"?\";\n }\n\n /**\n * Build multiple placeholders for MySQL.\n *\n * @param count - Number of placeholders needed\n * @param _startIndex - Starting index (ignored for MySQL)\n * @returns Comma-separated ? placeholders\n */\n protected buildPlaceholders(count: number, _startIndex: number = 0): string {\n return Array(count).fill(\"?\").join(\", \");\n }\n\n /**\n * Escape an identifier for MySQL (uses backticks instead of double quotes).\n *\n * @param identifier - The identifier to escape\n * @returns Escaped identifier with backticks\n */\n protected escapeIdentifier(identifier: string): string {\n // MySQL uses backticks for identifiers\n return `\\`${identifier.replace(/`/g, \"``\")}\\``;\n }\n\n // ============================================================\n // Protected Helper Methods\n // ============================================================\n\n /**\n * Ensures pool is connected and returns it.\n *\n * @throws {DatabaseError} If not connected\n */\n private ensurePool(): Pool {\n if (!this.pool) {\n throw createDatabaseError({\n kind: \"connection\",\n message: \"MySqlAdapter is not connected. Call connect() first.\",\n });\n }\n return this.pool;\n }\n\n /**\n * Return the typed Drizzle instance for MySQL.\n * Guarded for server-only usage and requires an active connection.\n *\n * @param schema - Optional schema for relational queries (db.query.*)\n * @returns Drizzle ORM instance wrapping the mysql2 pool connection\n * @throws {Error} If called in browser or not connected\n */\n getDrizzle<T = MySql2Database<AnyRelations>>(relations?: AnyRelations): T {\n if (typeof window !== \"undefined\") {\n throw new Error(\"getDrizzle() is server-only\");\n }\n const pool = this.ensurePool();\n if (!relations) {\n this.drizzleBare ??= this.poolDrizzle(pool);\n return this.drizzleBare as T;\n }\n let cached = this.drizzleByRelations.get(relations);\n if (!cached) {\n cached = this.poolDrizzle(pool, relations);\n this.drizzleByRelations.set(relations, cached);\n }\n return cached as T;\n }\n\n /**\n * A Drizzle handle on the pool, for `getDrizzle`.\n *\n * Its `transaction` runs on a connection this adapter checks out and\n * returns itself (`pinDrizzleTransactions`): destroyed rather than pooled\n * when no ROLLBACK could be confirmed on it. And it counts for\n * `transactionOpenInFlow`, as the adapter's does.\n */\n private poolDrizzle(pool: Pool, relations?: AnyRelations) {\n // drizzle v1's mysql2 driver takes the CALLBACK pool and connection,\n // which the mysql2/promise wrappers expose on `.pool` and `.connection`:\n // handed a wrapper, it throws (\"Cannot set properties of undefined\n // (setting 'supportBigNumbers')\"). The pre-v1 `mode` option is gone.\n const onClient = (client: CallbackPool | CallbackConnection) =>\n relations ? drizzle({ client, relations }) : drizzle({ client });\n // The handle's own queries go to the pool, so it is handed a view of the\n // pool that reports them (`observedPool`).\n const callbackPool = this.observedPool(\n (pool as unknown as { pool: CallbackPool }).pool,\n [\"query\", \"execute\", \"getConnection\"]\n );\n return this.trackFlowTransactions(\n this.pinDrizzleTransactions(onClient(callbackPool), async () => {\n const connection = await this.connectFlowTransaction(() =>\n pool.getConnection()\n );\n return {\n drizzle: onClient(\n (connection as unknown as { connection: CallbackConnection })\n .connection\n ),\n rollback: () => connection.query(\"ROLLBACK\"),\n release: dirty => {\n if (dirty) connection.destroy();\n else connection.release();\n },\n };\n })\n );\n }\n\n /**\n * Builds mysql2 Pool configuration from adapter config.\n */\n private buildPoolConfig(): PoolOptions {\n const config: PoolOptions = {};\n\n // Connection string or explicit options\n if (this.config.url) {\n config.uri = this.config.url;\n } else {\n if (this.config.host) config.host = this.config.host;\n if (this.config.port) config.port = this.config.port;\n if (this.config.database) config.database = this.config.database;\n if (this.config.user) config.user = this.config.user;\n if (this.config.password) config.password = this.config.password;\n }\n\n // Pool settings - mysql2 uses different property names\n config.connectionLimit = this.config.pool?.max ?? DEFAULT_POOL_CONFIG.max;\n config.idleTimeout =\n this.config.pool?.idleTimeoutMs ?? DEFAULT_POOL_CONFIG.idleTimeoutMs;\n config.connectTimeout =\n this.config.pool?.connectionTimeoutMs ??\n DEFAULT_POOL_CONFIG.connectionTimeoutMs;\n\n // A request waits for a connection when the pool is full. The queue has\n // no length limit; each wait in it is bounded instead (`boundPoolWait`).\n config.waitForConnections = true;\n config.queueLimit = 0;\n\n // SSL configuration\n if (this.config.ssl) {\n if (typeof this.config.ssl === \"boolean\") {\n config.ssl = this.config.ssl ? {} : undefined;\n } else {\n config.ssl = {\n rejectUnauthorized: this.config.ssl.rejectUnauthorized,\n ca: this.config.ssl.ca,\n cert: this.config.ssl.cert,\n key: this.config.ssl.key,\n };\n }\n }\n\n // MySQL-specific options\n if (this.config.timezone) {\n config.timezone = this.config.timezone;\n }\n\n if (this.config.charset) {\n config.charset = this.config.charset;\n }\n\n // Enable multiple statements if needed (disabled by default for security)\n config.multipleStatements = false;\n\n // Date handling\n config.dateStrings = false; // Return Date objects\n\n return config;\n }\n\n /**\n * Begins a transaction with the specified options, recording in `changed`\n * each session setting it changes, as it changes it, for `restoreSession`\n * to put back.\n */\n private async beginTransaction(\n connection: PoolConnection,\n options: TransactionOptions | undefined,\n changed: NonNullable<SessionRestore>\n ): Promise<void> {\n // Set isolation level if specified (must be done before BEGIN)\n if (options?.isolationLevel) {\n const isolationMap: Record<string, string> = {\n \"read uncommitted\": \"READ UNCOMMITTED\",\n \"read committed\": \"READ COMMITTED\",\n \"repeatable read\": \"REPEATABLE READ\",\n serializable: \"SERIALIZABLE\",\n };\n const level = isolationMap[options.isolationLevel];\n if (level) {\n await connection.query(`SET TRANSACTION ISOLATION LEVEL ${level}`);\n }\n }\n\n // Set read-only mode if specified\n if (options?.readOnly) {\n await connection.query(\"SET TRANSACTION READ ONLY\");\n }\n\n // Begin the transaction\n await connection.query(\"START TRANSACTION\");\n\n // Set lock wait timeout if specified\n if (options?.timeoutMs) {\n // Read first, so the session's own value can be put back once the\n // transaction has ended (`SessionRestore`).\n const [rows] = await connection.query<RowDataPacket[]>(\n \"SELECT @@SESSION.innodb_lock_wait_timeout AS timeout\"\n );\n const previous = Number(rows[0]?.timeout);\n // MySQL uses seconds for lock_wait_timeout\n const timeoutSeconds = Math.ceil(options.timeoutMs / 1000);\n await connection.query(\n `SET SESSION innodb_lock_wait_timeout = ${timeoutSeconds}`\n );\n changed.lockWaitTimeout = Number.isInteger(previous) ? previous : null;\n }\n\n // Strict mode for this transaction: an INSERT, UPDATE or ALTER that would\n // cut a string to its column's length, or clamp a number to its range,\n // fails instead of applying with a warning. Added to the session's own\n // mode, so every other flag it had still holds, and put back afterwards.\n if (options?.strictSqlMode) {\n const [rows] = await connection.query<RowDataPacket[]>(\n \"SELECT @@SESSION.sql_mode AS mode\"\n );\n const previous: unknown = rows[0]?.mode;\n await connection.query(\n \"SET SESSION sql_mode = TRIM(BOTH ',' FROM CONCAT(@@SESSION.sql_mode, ',STRICT_ALL_TABLES'))\"\n );\n changed.sqlMode = typeof previous === \"string\" ? previous : null;\n }\n }\n\n /**\n * Creates a TransactionContext for the given connection.\n *\n * @remarks\n * Note: Savepoint methods are not implemented (set to undefined)\n * as savepoints are disabled in this adapter per approved approach.\n */\n /**\n * Upsert with the meaning `INSERT … ON CONFLICT (target)` has on PostgreSQL\n * and SQLite, on the tables where MySQL can keep that promise.\n *\n * MySQL cannot limit a duplicate to one key: `ON DUPLICATE KEY UPDATE`\n * fires on a collision with ANY unique key, and a failed insert does not\n * say reliably which one. So the conflict target must be the table's only\n * unique key apart from its primary key, and any other table is refused\n * before anything is written. On such a table the row is inserted first —\n * its validation and triggers apply, as they do before `ON CONFLICT`\n * elsewhere — and a duplicate is resolved by a locking read of the target\n * key, which sees the latest committed row rather than the transaction's\n * snapshot. The row found is kept as it is when there is nothing to update\n * (a no-op assignment would still run its update triggers), or updated by\n * its key. No row there means the collision was on the primary key, and it\n * is refused as `ON CONFLICT (target)` refuses it.\n *\n * The steps run in the caller's transaction, or in one of their own, since a\n * locking read locks nothing past its statement under autocommit. Rows are\n * read back by their primary key, so a trigger that rewrites the conflict\n * value still returns the row stored. The conflict columns must also be\n * given values: MySQL cannot look a row up by a key the database would only\n * fill in itself. A conflict is resolved on the caller's key value: a\n * BEFORE INSERT trigger that moves the key onto another row's value is\n * refused as a unique violation rather than resolved onto that row. A failed insert rolls back only itself on MySQL, so a\n * caller's transaction stays usable.\n */\n override async upsert<T = unknown>(\n table: string,\n data: Record<string, unknown>,\n options: UpsertOptions,\n executor?: unknown\n ): Promise<T> {\n const tableObj = this.getTableObject(table) as MySqlTable | undefined;\n // Unknown table: the base method reports it as every CRUD method does.\n if (!tableObj) return super.upsert<T>(table, data, options, executor);\n let target: { where: SQL | undefined; nullKey: boolean };\n try {\n // Judged before anything else, so a refused call takes no connection.\n target = this.upsertTarget(tableObj, table, data, options);\n } catch (error) {\n throw this.handleQueryError(error, \"upsert\", table);\n }\n // A locking read holds its lock only inside a transaction: under autocommit\n // it is released when its own statement ends, and the next statement may\n // run on another pooled connection. Without the caller's transaction, the\n // insert, the read and the update get one of their own, on one connection.\n if (executor === undefined) {\n return this.transaction(tx => tx.upsert<T>(table, data, options));\n }\n try {\n const db = executor as MySql2Database<AnyRelations>;\n // A conflict key holding NULL never conflicts: a unique index admits any\n // number of NULLs. It is a plain insert, read back by its primary key.\n if (target.nullKey) {\n return ((await this.insertRow(db, tableObj, data)) ?? data) as T;\n }\n return (await this.insertOrResolve(\n db,\n tableObj,\n data,\n options,\n target.where\n )) as T;\n } catch (error) {\n throw this.handleQueryError(error, \"upsert\", table);\n }\n }\n\n /**\n * What an upsert is keyed on: the target's condition, and whether its key\n * holds a NULL. Refuses a target this dialect cannot keep to, and a conflict\n * column left for the database to fill — MySQL cannot look a row up by a key\n * value only the database would supply.\n */\n private upsertTarget(\n tableObj: MySqlTable,\n table: string,\n data: Record<string, unknown>,\n options: UpsertOptions\n ): { where: SQL | undefined; nullKey: boolean } {\n // MySQL needs every conflict value whether or not it updates: the row is\n // found by them after a duplicate, so the keep-existing rule applies to\n // every call here.\n this.assertUpsertTarget(table, data, options, true);\n const key = this.conflictKey(tableObj, table, options.conflictColumns);\n const values = options.conflictColumns.map(column => data[column]);\n return {\n where: and(...key.map((column, i) => eq(column, values[i] as never))),\n nullKey: values.some(value => value === null),\n };\n }\n\n /**\n * The table's columns for a conflict target, refusing a target MySQL cannot\n * keep to: one that is not a primary or unique key, which an update could\n * spread over several rows, and one beside which the table has another\n * unique key, a collision on which MySQL would not tell apart.\n */\n private conflictKey(\n tableObj: MySqlTable,\n table: string,\n conflictColumns: readonly string[]\n ): Column[] {\n const record = tableObj as unknown as Record<string, Column | undefined>;\n const columns = conflictColumns.map(name => record[name]);\n const names = new Set(columns.map(column => column?.name));\n const isTarget = (key: readonly string[]) =>\n key.length === names.size && key.every(name => names.has(name));\n const { primary, unique } = keysOf(tableObj);\n // Every row this upsert returns is read back by its primary key, so a\n // table without one has no stable way to find the row it wrote.\n if (primary.length === 0) {\n throw createDatabaseError({\n kind: \"query\",\n message: `upsert on ${table}: MySQL upserts need a table with a primary key, to read back the row they write.`,\n });\n }\n const known = columns.every(column => column !== undefined);\n if (\n !known ||\n !(isTarget(primary) || unique.some(k => isTarget(k.columns)))\n ) {\n throw createDatabaseError({\n kind: \"query\",\n message: `upsert on ${table}: the conflict columns (${conflictColumns.join(\", \")}) are not a primary or unique key of the table.`,\n });\n }\n const others = unique.filter(key => !isTarget(key.columns));\n if (others.length > 0) {\n throw createDatabaseError({\n kind: \"query\",\n message: `upsert on ${table}: MySQL cannot limit a duplicate to the conflict columns (${conflictColumns.join(\", \")}) while the table has other unique keys (${others.map(key => key.name).join(\", \")}). Upsert only on a table whose one unique key besides the primary key is the conflict target, or insert and update inside a transaction.`,\n });\n }\n return columns;\n }\n\n /** The update an upsert applies to an existing row: never its key. */\n private updateValues(\n data: Record<string, unknown>,\n options: UpsertOptions\n ): Record<string, unknown> {\n const key = new Set(options.conflictColumns);\n const update: Record<string, unknown> = {};\n for (const column of options.updateColumns ?? Object.keys(data)) {\n if (!key.has(column) && column in data) update[column] = data[column];\n }\n return update;\n }\n\n /** The row matching `where`, by a locking (current) read. */\n private async lockedRow(\n db: MySql2Database<AnyRelations>,\n tableObj: MySqlTable,\n where: SQL | undefined\n ): Promise<unknown> {\n const rows = await db\n .select()\n .from(tableObj)\n .where(where)\n .limit(1)\n .for(\"update\");\n return rows[0];\n }\n\n /**\n * Insert the row, or resolve a duplicate on the target key. The insert is\n * read back by the primary key it reports, not by the conflict key: a\n * BEFORE INSERT trigger may have rewritten the conflict value, and the row\n * stored is the one to return.\n *\n * A duplicate is resolved when a row holds the TARGET key, whichever unique\n * key MySQL names in its error. PostgreSQL checks the target's index before\n * any other, so a row colliding on the target and on another key resolves\n * on the target there too; refusing it here because MySQL happened to check\n * the other index first would answer that case differently. A target row\n * committed by another transaction after this insert failed is the order in\n * which that transaction ran first, where PostgreSQL also resolves on it.\n */\n private async insertOrResolve(\n db: MySql2Database<AnyRelations>,\n tableObj: MySqlTable,\n data: Record<string, unknown>,\n options: UpsertOptions,\n where: SQL | undefined\n ): Promise<unknown> {\n let failure: unknown;\n try {\n const stored = await this.insertRow(db, tableObj, data);\n return stored ?? (await this.lockedRow(db, tableObj, where));\n } catch (error) {\n // Classified as everything else is, through the driver's own error\n // under Drizzle's wrapper (`classifyError`).\n if (this.classifyError(error).kind !== \"unique_violation\") throw error;\n failure = error;\n }\n const existing = await this.lockedRow(db, tableObj, where);\n // No row holds the target key: the collision was on another unique key,\n // refused as `ON CONFLICT (target)` refuses it, as the unique violation the\n // classifier reads it to be.\n if (existing === undefined) throw failure;\n const update = this.updateValues(data, options);\n if (Object.keys(update).length === 0) return existing;\n await db.update(tableObj).set(update).where(where);\n // Read back by the row's primary key as the update left it: the update may\n // set the key itself (every given column is updated by default, as `ON\n // CONFLICT DO UPDATE` does elsewhere), and a BEFORE UPDATE trigger may\n // have changed the conflict value the update was keyed on. A trigger that\n // changed the primary key instead leaves the conflict value standing, so\n // the row is looked for there next; one that changed both is not found.\n const identity = this.byIdentity(tableObj, {\n ...(existing as Record<string, unknown>),\n ...update,\n });\n const updated =\n identity === undefined\n ? undefined\n : await this.lockedRow(db, tableObj, identity);\n return updated ?? this.lockedRow(db, tableObj, where);\n }\n\n /**\n * Insert a row and read it back by its primary key: the value the caller\n * gave, or the one MySQL or the model generated, which `$returningId()`\n * reports and a given value it does not. Undefined when the table has no\n * primary key to read by.\n */\n private async insertRow(\n db: MySql2Database<AnyRelations>,\n tableObj: MySqlTable,\n data: Record<string, unknown>\n ): Promise<unknown> {\n const [generated] = (await db\n .insert(tableObj)\n .values(data as never)\n .$returningId()) as Record<string, unknown>[];\n // A key the caller gave wins; one given as undefined or null does not hide\n // the value MySQL generated for it.\n const given = Object.fromEntries(\n Object.entries(data).filter(\n ([, value]) => value !== undefined && value !== null\n )\n );\n const identity = this.byIdentity(tableObj, { ...generated, ...given });\n return identity === undefined\n ? undefined\n : this.lockedRow(db, tableObj, identity);\n }\n\n /**\n * A row's primary key as a condition, from a record keyed as the model's\n * properties are. Undefined when the table has no primary key or the record\n * lacks part of it.\n */\n private byIdentity(\n tableObj: MySqlTable,\n record: Record<string, unknown>\n ): SQL | undefined {\n const primary = new Set(keysOf(tableObj).primary);\n const parts = Object.entries(getColumns(tableObj)).filter(([, column]) =>\n primary.has(column.name)\n );\n if (\n parts.length === 0 ||\n parts.some(\n ([name]) => record[name] === undefined || record[name] === null\n )\n ) {\n return undefined;\n }\n return and(\n ...parts.map(([name, column]) => eq(column, record[name] as never))\n );\n }\n\n /** A table-level `primaryKey({ columns })`, read through the MySQL table config. */\n protected override compositePrimaryKey(\n tableObj: Record<string, unknown>\n ): object[] {\n return getTableConfig(\n tableObj as unknown as MySqlTable\n ).primaryKeys.flatMap(key => key.columns);\n }\n\n private createTransactionContext(\n connection: PoolConnection\n ): TransactionContext {\n // Bind a Drizzle instance to this transaction's checked-out connection so\n // the delegated CRUD methods run inside the transaction and see its\n // uncommitted rows. drizzle's mysql2 driver needs the underlying CALLBACK\n // connection, which the mysql2/promise wrapper exposes on `.connection`\n // (mirrors the `.pool` unwrap in getDrizzle()); getDrizzle() itself wraps\n // the pool, which would use a different connection. Built lazily and\n // memoized: transactions that use only raw execute/insert never construct\n // it.\n const txConnection = (\n connection as unknown as { connection: CallbackConnection }\n ).connection;\n const txHandles = this.transactionDrizzleHandles(relations =>\n relations\n ? drizzle({ client: txConnection, relations })\n : drizzle({ client: txConnection })\n );\n const txDb = txHandles.bare;\n return {\n drizzleWithRelations: txHandles.withRelations,\n\n execute: async <T = unknown>(\n sql: string,\n params: SqlParam[] = []\n ): Promise<T[]> => {\n const [rows] = await connection.query<RowDataPacket[]>(\n sql,\n params as unknown[]\n );\n return rows as T[];\n },\n\n // Run on the transaction-bound Drizzle instance rather than the pool, so\n // the statement is part of this transaction and sees its uncommitted rows.\n runStatement: async (statement: SQL): Promise<void> => {\n await txDb().execute(statement);\n },\n\n // mysql2 answers a `[rows, fields]` tuple; the transaction-bound instance\n // keeps the read inside this transaction so it sees its uncommitted writes.\n queryStatement: async <T = Record<string, unknown>>(\n statement: SQL\n ): Promise<T[]> => {\n const result = await txDb().execute(statement);\n // A tuple's first element is the rows. Anything else was not understood,\n // and must not reach a caller as \"there is nothing there\" — the same\n // reason the pooled `queryStatement` refuses rather than answering\n // empty.\n if (!Array.isArray(result)) {\n throw this.createDatabaseError(\n \"query\",\n \"Drizzle statement returned a result shape this adapter does not recognise; refusing to report it as an empty result.\",\n undefined\n );\n }\n return result[0] as unknown as T[];\n },\n\n lockRow: async (table: string, id: SqlParam): Promise<void> => {\n const idColumn = this.escapeIdentifier(\"id\");\n await connection.query(\n `SELECT ${idColumn} FROM ${this.escapeIdentifier(table)} ` +\n `WHERE ${idColumn} = ? FOR UPDATE`,\n [id] as unknown[]\n );\n },\n\n insert: async <T = unknown>(\n table: string,\n data: Record<string, unknown>,\n options?: InsertOptions\n ): Promise<T> => {\n const mapped = this.mapRowToRawSql(this.getTableObject(table), data);\n const columns = Object.keys(mapped);\n const values = Object.values(mapped);\n const placeholders = this.buildPlaceholders(values.length, 0);\n\n const sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map(c => this.escapeIdentifier(c)).join(\", \")}) VALUES (${placeholders})`;\n\n const [result] = await connection.query<ResultSetHeader>(sql, values);\n\n const ret = options?.returning;\n // No columns requested: skip the select-back reread entirely.\n if (Array.isArray(ret) && ret.length === 0) {\n return undefined as T;\n }\n\n // MySQL has no RETURNING; select the inserted row back. Project only the\n // requested columns so a large JSON snapshot is not read unless asked.\n const insertTableObj = this.getTableObject(table);\n // Each timestamp's wall clock, spelled out by the database. mysql2\n // turns one into a `Date` in the LOCAL zone before this code sees it,\n // and that conversion cannot be undone: a wall clock inside a\n // daylight-saving gap is normalized away.\n const aliases = this.dateWallClockAliases(insertTableObj, ret ?? \"*\");\n const spelled = aliases\n .map(\n a =>\n `DATE_FORMAT(${this.escapeIdentifier(a.sqlName)}, '%Y-%m-%dT%H:%i:%s.%f') AS ${this.escapeIdentifier(a.alias)}`\n )\n .join(\", \");\n const projected =\n !ret || ret === \"*\"\n ? \"*\"\n : this.mapColumnNamesToSql(insertTableObj, ret)\n .map(c => this.escapeIdentifier(c))\n .join(\", \");\n const selectList = spelled ? `${projected}, ${spelled}` : projected;\n\n // Prefer the primary key: auto-increment via insertId, otherwise a\n // supplied id (manually-keyed tables like nextly_versions). Matching by\n // all values is a last resort because `col = NULL` never matches, so a\n // row with nullable columns would not be found by that path.\n const idValue = result.insertId ? result.insertId : mapped.id;\n if (idValue !== undefined) {\n const [rows] = await connection.query<RowDataPacket[]>(\n `SELECT ${selectList} FROM ${this.escapeIdentifier(table)} WHERE id = ?`,\n [idValue]\n );\n return this.mapRowFromRawSql(insertTableObj, rows[0] as T, aliases);\n }\n\n const whereClauses = columns.map(\n c => `${this.escapeIdentifier(c)} = ?`\n );\n const [rows] = await connection.query<RowDataPacket[]>(\n `SELECT ${selectList} FROM ${this.escapeIdentifier(table)} WHERE ${whereClauses.join(\" AND \")} LIMIT 1`,\n values\n );\n return this.mapRowFromRawSql(insertTableObj, rows[0] as T, aliases);\n },\n\n insertMany: async <T = unknown>(\n table: string,\n data: Record<string, unknown>[],\n options?: InsertOptions\n ): Promise<T[]> => {\n if (data.length === 0) return [];\n const retMany = options?.returning;\n const skipReread = Array.isArray(retMany) && retMany.length === 0;\n\n const tableObj = this.getTableObject(table);\n const mappedRecords = data.map(r => this.mapRowToRawSql(tableObj, r));\n const columns = Object.keys(mappedRecords[0]);\n const allValues: unknown[] = [];\n const valuesClauses: string[] = [];\n\n for (const record of mappedRecords) {\n const placeholders: string[] = [];\n for (const col of columns) {\n allValues.push(record[col]);\n placeholders.push(\"?\");\n }\n valuesClauses.push(`(${placeholders.join(\", \")})`);\n }\n\n const sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map(c => this.escapeIdentifier(c)).join(\", \")}) VALUES ${valuesClauses.join(\", \")}`;\n\n const [result] = await connection.query<ResultSetHeader>(\n sql,\n allValues\n );\n\n // For bulk insert, we need to SELECT the inserted rows\n // MySQL's insertId gives the first auto-increment ID\n if (!skipReread && result.insertId && result.affectedRows > 0) {\n const ids: number[] = [];\n for (let i = 0; i < result.affectedRows; i++) {\n ids.push(result.insertId + i);\n }\n const placeholders = ids.map(() => \"?\").join(\", \");\n const bulkAliases = this.dateWallClockAliases(tableObj, \"*\");\n const bulkSpelled = bulkAliases\n .map(\n a =>\n `DATE_FORMAT(${this.escapeIdentifier(a.sqlName)}, '%Y-%m-%dT%H:%i:%s.%f') AS ${this.escapeIdentifier(a.alias)}`\n )\n .join(\", \");\n const [rows] = await connection.query<RowDataPacket[]>(\n `SELECT *${bulkSpelled ? `, ${bulkSpelled}` : \"\"} FROM ${this.escapeIdentifier(table)} WHERE id IN (${placeholders})`,\n ids\n );\n return (rows as T[]).map(r =>\n this.mapRowFromRawSql(tableObj, r, bulkAliases)\n );\n }\n\n // Fallback: return empty if we can't determine inserted rows\n return [];\n },\n\n // Adapter-built, as `insert` above is; `transactionUpdate` says why.\n // A column the model does not declare binds natively, as every value\n // on this path's insert does.\n update: this.transactionUpdate(\n txDb,\n async statement => {\n // No RETURNING on MySQL: nothing to report, the read-back is by\n // the caller's predicate.\n await txDb().execute(statement);\n return undefined;\n },\n // Structured values as JSON text: mysql2's formatter spells an object\n // as `key = value` pairs and an array as a value list, neither JSON.\n value => this.bindUnmodeledStructuredAsJson(value)\n ),\n\n ...this.createTransactionForwarders(txDb),\n\n // Savepoints disabled per approved approach\n savepoint: undefined,\n rollbackToSavepoint: undefined,\n releaseSavepoint: undefined,\n };\n }\n\n /**\n * Classifies a MySQL error into a DatabaseError.\n *\n * @param error - Original error from mysql2\n * @param sql - SQL statement that caused the error (optional)\n * @returns DatabaseError with proper classification\n */\n protected override classifyError(\n error: unknown,\n sql?: string\n ): DatabaseError {\n // Why short-circuit on existing DatabaseError: F17's\n // UnsupportedDialectVersionError is already a typed DatabaseError with\n // kind: \"unsupported_version\" plus detectedVersion/requiredVersion\n // fields. Re-wrapping it here would erase those fields and re-tag it\n // as kind: \"unknown\".\n if (isDatabaseError(error)) return error;\n\n // Classified from mysql2's own error, which Drizzle puts on `cause` when it\n // wraps a failed query (`driverErrorIn`); it is the one carrying `errno`.\n const mysqlError = this.driverErrorIn<{\n errno?: number;\n code?: string;\n sqlState?: string;\n message?: string;\n sql?: string;\n cause?: unknown;\n }>(error, candidate => typeof candidate.errno === \"number\");\n\n // Determine error kind from MySQL error number\n const kind: DatabaseErrorKind =\n (mysqlError.errno && MYSQL_ERROR_CODES[mysqlError.errno]) || \"unknown\";\n\n // Build error message\n let message = mysqlError.message ?? String(error);\n if (sql && kind === \"query\") {\n message = `Query failed: ${message}`;\n }\n\n return createDatabaseError({\n kind,\n message,\n code: mysqlError.code ?? mysqlError.errno?.toString(),\n detail: mysqlError.sql,\n cause: error instanceof Error ? error : undefined,\n });\n }\n}\n\n/** A table's keys by database column name, as its model declares them. */\ninterface TableKeys {\n primary: string[];\n unique: { name: string; columns: string[] }[];\n}\n\nconst TABLE_KEYS = new WeakMap<MySqlTable, TableKeys>();\n\n/**\n * A table's primary key and its unique keys other than the primary key, read\n * from its model once and kept for the table's lifetime: a model is not\n * changed in place, a new schema brings new table objects.\n */\nfunction keysOf(tableObj: MySqlTable): TableKeys {\n const cached = TABLE_KEYS.get(tableObj);\n if (cached) return cached;\n const config = getTableConfig(tableObj);\n const primary = [\n ...config.columns.filter(column => column.primary),\n ...config.primaryKeys.flatMap(key => key.columns),\n ].map(column => column.name);\n const unique = [\n ...config.columns\n .filter(column => column.isUnique && !column.primary)\n .map(column => ({\n // Drizzle's own name for an unnamed column-level unique key.\n name: column.uniqueName ?? `${config.name}_${column.name}_unique`,\n columns: [column.name],\n })),\n ...config.uniqueConstraints.map(constraint => ({\n name: constraint.name,\n columns: constraint.columns.map(column => column.name),\n })),\n ...config.indexes\n .filter(index => index.config.unique === true)\n .map(index => ({\n name: index.config.name,\n columns: (index.config.columns as { name: string }[]).map(\n column => column.name\n ),\n })),\n ];\n const keys = { primary, unique };\n TABLE_KEYS.set(tableObj, keys);\n return keys;\n}\n\n/**\n * Create a MySQL database adapter.\n *\n * @param config - MySQL adapter configuration\n * @returns A new MySqlAdapter instance\n *\n * @example\n * ```typescript\n * // Simple usage with URL\n * const adapter = createMySqlAdapter({\n * url: 'mysql://user:pass@localhost:3306/mydb',\n * });\n *\n * // Full configuration\n * const adapter = createMySqlAdapter({\n * url: process.env.DATABASE_URL!,\n * pool: {\n * min: 2,\n * max: 20,\n * idleTimeoutMs: 30000,\n * connectionTimeoutMs: 10000,\n * },\n * ssl: {\n * rejectUnauthorized: true,\n * },\n * });\n *\n * await adapter.connect();\n * ```\n */\nexport function createMySqlAdapter(config: MySqlAdapterConfig): MySqlAdapter {\n return new MySqlAdapter(config);\n}\n\n/**\n * Type guard to check if a value is a MySqlAdapter.\n *\n * @param value - Value to check\n * @returns True if value is a MySqlAdapter instance\n *\n * @example\n * ```typescript\n * if (isMySqlAdapter(adapter)) {\n * // TypeScript knows adapter is MySqlAdapter\n * console.log('Using MySQL');\n * }\n * ```\n */\nexport function isMySqlAdapter(value: unknown): value is MySqlAdapter {\n return value instanceof MySqlAdapter;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAS,WAAW,MAAoB,SAAgC;CACtE,MAAM,QAAQ,KAAK;CACnB,IAAI,CAAC,OAAO,OAAO;CACnB,KAAK,IAAI,KAAK,GAAG,KAAK,MAAM,QAAQ,MAClC,IAAI,MAAM,OAAO,EAAE,MAAM,SAAS;EAChC,MAAM,UAAU,EAAE;EAClB,OAAO;CACT;CAEF,OAAO;AACT;;;;;;;;;;;;;;;AAgBA,SAAgB,cACd,MACA,SACG;CACH,IAAI,WAAW,GAAG,OAAO;CACzB,MAAM,gBAAgB,KAAK,cAAc,KAAK,IAAI;CAClD,MAAM,WAAW,aAAoC;EACnD,IAAI,WAAW;EAEf,MAAM,OAAkD,CAAC;EAGzD,IAAI,SAAS;EACb,MAAM,kBAAmB,SAAS;E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